我们在密码处输入的所有内容都应该是密码的组成。
但是现在Statement对象在执行sql语句时,将密码的一部分内容当做查询条件来执行了。
// 将用户输入的账号密码拼接后
SELECT * FROM user WHERE name='hehe' AND password='a'or'1'='1';
Statement的子接口PreparedStatement
PreparedStatement预编译执行者对象
预编译:SQL语句在执行前就已经编译好了,执行速度更快。
安全性更高:没有字符串拼接的SQL语句,所以避免SQL注入的问题
代码的可读性更好,因为没有字符串拼接
PreparedStatement使用
SQL语句中的参数使用?作为占位符
给?占位符赋值
设置参数
setXxx(参数1,参数2); Xxx代表:数据类型
参数1:第几个? (编号从1开始)
参数2:?的实际参数
执行SQL语句
int executeUpdate(); 执行insert、update、delete语句
ResultSet executeQuery(); 执行select语句
public static void main(String[] args) throws SQLException {Scanner scanner = new Scanner(System.in);System.out.println("请输入账号密码:");String name = scanner.next();String password = scanner.next();// 1.获取连接Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/db1?useSSL=false&useUnicode=true&characterEncoding=UTF8&serverTimezone=GMT","root","1234");// 2.编写参数化SQL(带?的SQL语句)String sql = "select * from account where name = ? and balance = ?";PreparedStatement prepareStatement = connection.prepareStatement(sql);// 3.给?赋值//数字1代表第一个?prepareStatement.setString(1,name);prepareStatement.setString(2,password);// 4.执行ResultSet resultSet = prepareStatement.executeQuery();if(resultSet.next()){System.out.println("成功");}else{System.out.println("失败");}// 5.释放资源resultSet.close();prepareStatement.close();connection.close();}
如果你对本文有疑问,你可以在文章下方对我留言,敬请指正,对于每个留言我都会认真查看。