预编译
package csdn.prepare.take;import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;public class TestCompiling {public static void main(String[] args) {prepare();}public static void prepare() {Connection conn = null;PreparedStatement ps = null;ResultSet rs = null;try {Class.forName("oracle.jdbc.OracleDriver");String url = "jdbc:oracle:thin:@127.0.0.1:1521:orcl";conn = DriverManager.getConnection(url, "scott", "scott");String sql = "select * from Users where UNAME = ? and UPASS = ?";// 预编译命令对象。 ps = conn.prepareStatement(sql);// 给sql里面的?赋值 // 这里有一个sql注入 ps.setString(1, "'123' or 1=1 --");ps.setString(2, "456");/*ps.setString(1, "rye");ps.setString(2, "999");*/// 这里易错 ps 继承了父类的 executeUpdate(sql)rs = ps.executeQuery();if (rs.next())System.out.println("登录成功");else System.out.println("登录失败");} catch (ClassNotFoundException e) {e.printStackTrace();} catch (SQLException e) {e.printStackTrace();} finally {try {if (rs != null)rs.close();if (ps != null)ps.close();if (conn != null)conn.close();} catch (SQLException e) {e.printStackTrace();}}}}
批处理
package csdn.prepare.take;import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;public class TestBatch {public static void main(String[] args) {// 批处理 和 预编译。batch();//批处理就是把多条数据打包好, 再把数据一次性放入SQL里面。}public static void batch() {Connection conn = null;PreparedStatement ps = null;try {Class.forName("oracle.jdbc.OracleDriver");String url = "jdbc:oracle:thin:@127.0.0.1:1521:orcl";long start = System.currentTimeMillis();conn = DriverManager.getConnection(url, "scott", "scott");String sql = "insert into Users values (?, ?, ?)";// 预编译对象ps = conn.prepareStatement(sql);// 我要添加多个对象 用到批处理for (int i = 4; i < 1000000; i++) {ps.setInt(1, i);ps.setString(2, "" + i);ps.setString(3, "" + i); // 把一条SQL语句添加到批处理命令中。ps.addBatch();} // 预编译对象执行批处理 返回int数组int[] batchs = ps.executeBatch();long end = System.currentTimeMillis();System.out.println("用时" + (end - start) + "毫秒");System.out.println(batchs.length);} catch (ClassNotFoundException e) {e.printStackTrace();} catch (SQLException e) {e.printStackTrace();} finally {try {if (ps != null)ps.close();if (conn != null)conn.close();} catch (SQLException e) {e.printStackTrace();}}}}
users表结构如下
插入了999996条数据 用了
如果比直接插入不用批处理和预编译快多了。