PreparedStatement(防止SQL注入)
PreparedStatement防lsQL注入的本质,把传递进来的参数当做字符
假设其中存在转义字符,比如说‘会被直接转义
package com.zhaoyang;
import com.zhaoyang.utils.JdbcUtils;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class PreparedStatements {
public static void main(String[] args) {
Connection connection = null;
PreparedStatement pstm = null;
try {
connection = JdbcUtils.getConnection ();
//区别
//使用? 占位符代替参数
String sql = "insert into users(id,`name`,`password`,`email`,`birthday`) values(?,?,?,?,?)";
pstm = connection.prepareStatement (sql);//预编译SQL,先写sql但不执行
//手动给参数赋值
pstm.setInt (1,5);
pstm.setString (2,"zhaoyang");
pstm.setString (3,"123456");
pstm.setString (4,"1422320948@qq.com");
//两个Date不一样 newDate().getTime() 获得时间戳
pstm.setDate (5,new Date (new java.util.Date ().getTime ()) );
//执行
int i = pstm.executeUpdate ();
if (i>0){
System.out.println ("插入成功");
}
} catch (SQLException throwables) {
throwables.printStackTrace ();
} finally {
JdbcUtils.release (connection,pstm,null);
}
}
}