import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Scanner;
public class Test04 {
public static void main(String[] args) {
//初始化一个界面
Map<String,String> userLoginInfo = initUI();
//验证用户名和密码
boolean loginSuccess = login(userLoginInfo);
//输出结果
System.out.println(loginSuccess ? "登陆成功" : "登陆失败");
}
/**
* 用户登录
* @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");
//JDBC代码
//获取资源绑定器对象
ResourceBundle bundle = ResourceBundle.getBundle("jdbc");
String driver = bundle.getString("driver");
String url = bundle.getString("url");
String user = bundle.getString("user");
String password = bundle.getString("password");
ResultSet rs = null;
Statement stmt = null;
Connection conn = null;
try {
//1.注册驱动
Class.forName(driver);
//2.获取连接
conn = DriverManager.getConnection(url, user, password);
//3.获取数据库操作对象
stmt = conn.createStatement();
//4.执行sql
rs = stmt.executeQuery("select * from t_user where loginName = '"+loginName+"' and loginPwd = '"+loginPwd+"'");
//5.处理结果集
if (rs.next()){
//登陆成功
loginSuccess = true;
}
//6.释放资源
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return loginSuccess;
}
/**
*初始化用户界面
* @return 用户输入的用户名和密码等登录信息
*/
private static Map<String, String> initUI() {
Scanner s = new Scanner(System.in);
//得用户名
System.out.println("用户名:");
String loginName = s.nextLine();
//得密码
System.out.println("密码:");
String loginPwd = s.nextLine();
//将数据组装到Map集合中
Map<String,String> userLoginInfo = new HashMap<>();
userLoginInfo.put("loginName",loginName);
userLoginInfo.put("loginPwd",loginPwd);
//返回值
return userLoginInfo;
}
}
结果:
java.sql.SQLSyntaxErrorException: Unknown column 'loginName' in 'where clause'
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.StatementImpl.executeQuery(StatementImpl.java:1198)
at Test04.login(Test04.java:47)
at Test04.main(Test04.java:13)
登陆失败
Process finished with exit code 0
列名不存在或者在数据库找不到,先查看数据库 ,检查sql语句是不是错误
这错误提示还不够明显吗。用点心吧。java.sql.SQLSyntaxErrorException: Unknown column 'loginName' in 'where clause'