java中PreparedStatement用法和HelloWorld例子



1.PreparedStatement的HelloWorld程序


除 了Statement以外,Sun公司还提供了另外一个工具PreparedStatement,它们两个的效率比较,我们下一节再说,本节我们只讲 helloworld。PreparedStatement的用法就是:PreparedStatement中的SQL语句,可有一个或多个参数。每个参 数用一个问号(“?”)来占位。之后每个问号的值必须通过适当的setXXX方法来提供。

例:2.1.1

import java.io.IOException;

public class TestMark_to_win {

    public static void main(String[] args) throws java.sql.SQLException,

            ClassNotFoundException, IOException {

        java.sql.Connection connection = null;

        java.sql.PreparedStatement pstmt;

        Class.forName("com.mysql.jdbc.Driver");

        connection = java.sql.DriverManager.getConnection(

                "jdbc:mysql://localhost:3306/test", "root", "1234");

        pstmt = connection.prepareStatement("UPDATE login SET name = ? WHERE id = ?");


        pstmt.setString(1, "qqq");

        pstmt.setString(2, "1");

/*缺了下面这句,id为1的这一列更新不了了 */

        pstmt.executeUpdate();


        pstmt.setString(1, "qqqq");

        pstmt.setString(2, "2");

        pstmt.executeUpdate();


        pstmt.close();

        System.out.println("ok");

        connection.close();

    }

}