1. 程式人生 > 其它 >JDBC預處理

JDBC預處理

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();
}
}