1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
| import java.sql.*; import java.util.HashMap; import java.util.Map; import java.util.Scanner;
public class JDBCTest07 { public static void main(String[] args) { Map<String, String> userLoginInfo = initUI(); boolean loginSuccess = login(userLoginInfo); System.out.println(loginSuccess ? "登录成功" : "登录失败"); }
private static boolean login(Map<String, String> userLoginInfo) { String loginname = userLoginInfo.get("loginName"); String loginpwd = userLoginInfo.get("loginPwd"); boolean loginSuccess = false; Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode", "root", "123");
String sql = "select * from t_user where loginname = ? and loginpwd = ?";
ps = conn.prepareStatement(sql); ps.setString(1, loginname); ps.setString(2, loginpwd); rs = ps.executeQuery(); System.out.println(sql); if(rs.next()) { System.out.println(rs.getString("loginname")); System.out.println(rs.getString("realname")); loginSuccess = true; }
} catch (Exception e) { e.printStackTrace(); } finally { if(rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if(ps != null) { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } if(conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } }
return loginSuccess; }
private static Map<String, String> initUI() { Scanner in = new Scanner(System.in); System.out.println("用户名:"); String loginName = in.nextLine(); System.out.println("密码:"); String loginPwd = in.nextLine(); Map<String, String> userLoginInfo = new HashMap<String, String>(); userLoginInfo.put("loginName", loginName); userLoginInfo.put("loginPwd", loginPwd); return userLoginInfo; } }
|