zoukankan      html  css  js  c++  java
  • JDBC之Statement与preparedStatement

    用Statement执行数据库语句比较麻烦。

    例如,向数据库中插入整型, 字符串等数据。

     1 String JDriver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
     2         String connectDB="jdbc:sqlserver://ABYSS-
     3                 PC\\MYABYSS:64160;DatabaseName=master";
     4         //实例化驱动
     5         Class.forName(JDriver);
     6         String user ="sa";
     7         String possword = "";
     8         //连接数据库
     9         Connection conn = 
    10 DriverManager.getConnection(connectDB, user, possword);
    11         //创建语句对象
    12         Statement stmt = conn.createStatement();
    13         int Number = 189;
    14         String City = "北京";
    15         String Job = "服务业";
    16         String sql = "insert into dept2 values (" +
    17                      Number+",'" + City +"','"+ Job+"')";
    18         stmt.executeUpdate(sql);

    在sql变量中又是单引号 又是逗号的很麻烦,而且一不小心容易写错。

    换成preparedStatement就简单许多了

     1         String JDriver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
     2         String connectDB="jdbc:sqlserver://ABYSS-
     3 PC\\MYABYSS:64160;DatabaseName=master";
     4         //实例化驱动
     5         Class.forName(JDriver);
     6         String user ="sa";
     7         String possword = "";
     8         //连接数据库
     9         Connection conn = 
    10 DriverManager.getConnection(connectDB, user, possword);
    11         //创建语句对象
    12         int Number = 189;
    13         String City = "北京";
    14         String Job = "服务业";
    15         PreparedStatement pstmt =
    16         conn.prepareStatement( "insert into dept2 values (?, ?, ?)");
    17         pstmt.setInt(1, Number);
    18         pstmt.setString(2, City);
    19         pstmt.setString(3, Job);
    20         pstmt.executeUpdate();


  • 相关阅读:
    web测试方法总结
    APP测试点总结
    函数初识
    字符编码及文件操作
    简单购物车程序(Python)
    基本数据类型(列表,元祖,字典,集合)
    python基础
    基本数据类型(数字和字符串)
    Python入门
    操作系统
  • 原文地址:https://www.cnblogs.com/freeabyss/p/3187060.html
Copyright © 2011-2022 走看看