一、Statement
public class StatementLogin {
public static void main(String[] args) throws Exception {
//(1)键盘输入事件,收集账号和密码信息
Scanner scanner = new Scanner(System.in);
System.out.println("请输入你的账号:");
String account = scanner.nextLine();
System.out.println("请输入你的密码:");
String password = scanner.nextLine();
//(2)注册驱动
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
// (3)建立连接
Connection connection=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/jdbc1","root","123456");
Properties info = new Properties();
info.put("user","root");
info.put("password","root");
//(4)创建statement
//statement可以发送sql语句到数据库,并且获取返回结果
Statement statement = connection.createStatement();
//(5)发送sql语句,并获得返回结果(1.编写sql语句 2.发送sql语句)
String sql="select * from t_user where account='"+account+"' and PASSWORD = '"+password+"';";
ResultSet resultSet = statement.executeQuery(sql);
//移动一次光标,只要有数据,就代表登录成功
if(resultSet.next()){
System.out.println("登录成功");
}else{
System.out.println("登录失败");
}
//(7)关闭资源
resultSet.close();
statement.close();
connection.close();
}
}
二、PreparedStatement预编译
public class PrepareStatementLogin {
public static void main(String[] args) throws Exception {
//1.(1)收集用户信息
Scanner scanner = new Scanner(System.in);
System.out.println("请输入你的账号:");
String account = scanner.nextLine();
System.out.println("请输入你的密码:");
String password = scanner.nextLine();
//2.ps的数据库流程
//(1)注册驱动
Class.forName("com.mysql.jdbc.Driver");
//(2)获取连接
Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/jdbc1", "root", "123456");
//3.编写sql语句结果
String sql="select * from t_user where account=?and password=?;";
//4.创建预编译statement并且设置sql语句结果
PreparedStatement preparedStatement = connection.prepareStatement(sql);
//5.发送sql语句,并获取返回结果
ResultSet resultSet = preparedStatement.executeQuery();
//6.结果解析
if(resultSet.next()){
System.out.println("登陆成功");
}else{
System.out.println("登录失败");
}
//7.关闭资源
resultSet.close();
preparedStatement.close();
connection.close();
}
}
总结:
Statement不能预防注入攻击
PrepareedStatement预编译可以防止注入攻击