package com.hspedu.jdbc.preparedStatement_;
import java.io.FileInputStream;
import java.sql.*;
import java.util.Properties;
import java.util.Scanner;
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(); //若使用next(),当接收到空格或者'就表示结束
System.out.print("请输入管理员的密码:");
String admin_pwd = scanner.nextLine(); //如果想要看到SQL注入效果,这里需要用nextLine()
//通过Properties对象获取配置文件的信息
Properties properties = new Properties();
properties.load(new FileInputStream("src/mysql.properties"));
//读取相关的值
String driver = properties.getProperty("driver");
String url = properties.getProperty("url");
String user = properties.getProperty("user");
String password = properties.getProperty("password");
//1.注册驱动
Class.forName(driver);
//2.得到连接
Connection connection = DriverManager.getConnection(url, user, password);
//3.得到Statement
//3.1.sql语句,sql语句的?就相当于占位符
String sql = "select name, pwd from admin where name = ? and pwd = ?";
//3.2.preparedStatement对象实现了PreparedStatement接口的实现类的对象
PreparedStatement preparedStatement = connection.prepareStatement(sql);
//3.3.给?赋值
preparedStatement.setString(1, admin_name);
preparedStatement.setString(2, admin_pwd);
//4.执行select语句使用executeQuery
// 如果执行的是dml(update, insert, delete) executeUpdate()
ResultSet resultSet = preparedStatement.executeQuery(); //这里执行executeQuery, 不用再传入sql语句,否则传进去的是最初的sql语句
if (resultSet.next()) { //如果查询到一条记录,则说明该管理存在
System.out.println("恭喜,登录成功");
} else {
System.out.println("抱歉,登录失败");
}
//关闭连接
resultSet.close();
connection.close();
preparedStatement.close();
}
}
输出:
PreparedStatement的好处: