PreparedStatement 防止sql注入
- PreparedStatement 防止sql注入的本质,把传递进来的参数当做字符
- 假设其中存在转义字符,比如说 ` 会直接直接转义
package JDBCmysql.Demo03;
import JDBCmysql.Demo02.Demo01;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* PreparedStatement 防止sql注入的本质,把传递进来的参数当做字符
*假设其中存在转义字符,比如说 ` 会直接直接转义
* @author liu
*/
public class preparedStatementA {
public static void main(String[] args) {
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
//区别
//使用? 占位符代替参数
connection = Demo01.getTConnection();
//预编译sql,先写sql,然后不执行
String sql = "INSERT INTO users (id,name,psw, email, birthday)" + "VALUES(?,?,?,?,?);";
//手动给参数赋值
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1, 5);
preparedStatement.setString(2, "xiaowang");
preparedStatement.setObject(3, "123456");
preparedStatement.setString(4, "22222@222.com");
//注意点 sql。date 数据库类型的时间 java.sql.Date()
// util.date java类型的时间 new Date().getTime()
preparedStatement.setDate(5, new java.sql.Date(new java.util.Date().getTime()));
int i = preparedStatement.executeUpdate();
if (i > 0) {
System.out.println("插入成功");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
Demo01.Cclose(null, preparedStatement, connection);
}
}
}