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