import java.sql.*;
import java.util.*;
public class JDBCTest01 {
public static void main(String[] args) {
//初始化界面
Map<String, String> userLoginInfo = initUO();
boolean loginSuccess = login(userLoginInfo);
System.out.println("登陆成功!");
}
/**
* 用户登录
* @param userLoginInfo 用户登录信息
* @return false表示失败,true表示成功
*/
private static boolean login(Map<String, String> userLoginInfo) {
//标记
boolean loginSuccess = false;
//定义变量
String loginName = userLoginInfo.get("loginName");
String loginPwd = userLoginInfo.get("loginPwd");
Connection connection =null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
ResourceBundle bundle = ResourceBundle.getBundle("jdbc");
String driver =bundle.getString("driver");
String url =bundle.getString("url");
String username =bundle.getString("user");
String password =bundle.getString("password");
//JDBC
try {
Class.forName(driver);
connection = DriverManager.getConnection(url,username,password);
String sql = "select * from t_user where loginName = ? and loginPwd = ?;";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1,loginName);
preparedStatement.setString(2,loginPwd);
resultSet = preparedStatement.executeQuery();
if (resultSet.next()){
loginSuccess = true;
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
if (connection != null) {
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
return loginSuccess;
}
/**
* 初始化用户界面
*
* @return 用户输入的用户名和密码等登录信息
*/
private static Map<String, String> initUO() {
Scanner s = new Scanner(System.in);
System.out.print("用户名:");
String loginName = s.nextLine();
System.out.print("密码:");
String password = s.nextLine();
Map<String, String> userLoginInfo = new HashMap<>();
userLoginInfo.put("loginName", loginName);
userLoginInfo.put("loginPwd", password);
return userLoginInfo;
}
}