1.概述
出现SQL注入攻击的现象
问题原因:用户输入了非法字符#,#在SQL语句是注释的意思,改变21了SQL语义
preparedStatement 安全高效
2.写法改造
package cn.tedu.test;
import java.sql.*;
import java.util.Scanner;
/*自己准备user2表(id/name/password),准备数据
CREATE TABLE `user` (
`id` int(11) PRIMARY KEY auto_increment,
`name` varchar(10) default NULL,
`password` varchar(10) default NULL
) ;
*/
public class Test4 {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
System.out.println("请输入您的账号:");
String uname = new Scanner(System.in).nextLine();
System.out.println("请输入您的密码:");
String upassword = new Scanner(System.in).nextLine();
//注册驱动
Class<?> aClass = Class.forName("com.mysql.jdbc.Driver");
//获取连接
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/cgb2106",
"root", "root");
//获取传输 sql骨架
PreparedStatement preparedStatement = connection.prepareStatement("select * from user where name =? and password =?");
preparedStatement.setString(1,uname);
preparedStatement.setString(2,upassword);
//执行sql
ResultSet r = preparedStatement.executeQuery();
//验证
if (r.next()) {
System.out.println("登录成功!");
} else {
System.out.println("登录失败!请重新输入");
}
//关闭资源
preparedStatement.close();
connection.close();
}
}