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();
    }
}

更多内容请见原文,文章转载自:https://blog.csdn.net/qq_43650923/article/details/101098984

posted @ 2021-10-16 20:25  小龙虾1  阅读(206)  评论(0)    收藏  举报