public class PreparedStatement_ {
public static void main(String[] args) throws Exception{
Scanner scanner = new Scanner(System.in);
//让用户输入管理员名和密码
System.out.print("请输入管理员名字");
String admin_name = scanner.nextLine();//如果希望看到注入效果
System.out.print("请输入管理员密码");
String admin_pwd = scanner.nextLine();
Properties properties = new Properties();
properties.load(new FileInputStream("src\\mysql.properties"));
//获取相关的值(读取配置文件)
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String driver = properties.getProperty("driver");
String url = properties.getProperty("url");
//1.注册驱动
Class.forName(driver);
//2.得到链接
Connection connection = DriverManager.getConnection(url, user, password);
//3.得到PreparedStatement
//3.1组织Sql语句 sql的? 想让与占位符
String sql = "select name, pwd from admin where name =? and pwd = ?";
//3.2preparedStatement 对象实现了 PreparedStatement 接口的实现类的对象
PreparedStatement preparedStatement = connection.prepareStatement(sql);
//3.3
preparedStatement.setString(1,admin_name);
preparedStatement.setString(2,admin_pwd);
//4.执行select语句使用 excuteQuery
// 如果执行的是 dml(update, insert, delete) 使用executeUpdate
// 这里执行 excuteQuery 不要再写 sql
ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.next()){//如果查询到一条记录则说明该管理员存在
System.out.println("恭喜, 登陆成功");
}else {
System.out.println("登陆失败");
}
//关闭连接
resultSet.close();
preparedStatement.close();
connection.close();
}
}