
| 方式 | Statement | PreparedStatement | CallableStatement |
|---|---|---|---|
| 原理 | 用于执行静态SQL语句并返回他所生成的对象 | SQL语句被预编译并存储在此对象中,可以使用此对象多次高效地执行该语句。 | 用于执行SQL存储过程 |
| 不足 | sql注入、无法操作Blob二进制大数据如图片 | 可操作Blob |
sql注入: 因为sql语句是拼接字符串,所以会导致注释内如果填对了,就会导致登入成功
1.读取配置文件中的4个基本信息,连接数据库
2.加载驱动
3.获取连接
4.预编译sql语句,返回PreparedStatement的实例
5.填充占位符
6.执行操作
7.资源的关闭
// 向customers表中添加一条记录@Testpublic void testInsert() {Connection conn = null;PreparedStatement ps = null;try {// 1.读取配置文件中的4个基本信息InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");Properties pros = new Properties();pros.load(is);String user = pros.getProperty("user");String password = pros.getProperty("password");String url = pros.getProperty("url");String driverClass = pros.getProperty("driverClass");// 2.加载驱动Class.forName(driverClass);// 3.获取连接conn = DriverManager.getConnection(url, user, password);// System.out.println(conn);//4.预编译sql语句,返回PreparedStatement的实例String sql = "insert into customers(name,email,birth)values(?,?,?)";//?:占位符ps = conn.prepareStatement(sql);//5.填充占位符ps.setString(1, "哪吒");ps.setString(2, "nezha@gmail.com");SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");java.util.Date date = sdf.parse("1000-01-01");ps.setDate(3, new Date(date.getTime()));//6.执行操作ps.execute();} catch (Exception e) {e.printStackTrace();}finally{//7.资源的关闭try {if(ps != null)ps.close();} catch (SQLException e) {e.printStackTrace();}try {if(conn != null)conn.close();} catch (SQLException e) {e.printStackTrace();}}}