这是今天结合所学内容写的一个小程序
登录
1. 获取用户输入的用户名, 根据用户名查找数据库中是否存在该记录.
2. 如果没有找到, 提示用户名不存在重新输入.
3. 如果存在, 将数据库中数据封装成User对象返回.
4. 获取用户输入的密码, 和User对象密码进行比较, 如果不同则提示重新输入.
5. 密码正确提示登录成功, 将User中name,email, birthday显示.
import java.sql.*; import java.util.Scanner;
public class Login { String userName = ""; String password = "";
public Login() { getInfo(); Connection con = null; Statement stmt = null; ResultSet rs = null;
try { con = DriverManager.getConnection("jdbc:mysql://localhost/loginDb", "root", "admin"); stmt = con.createStatement(); String sql = "select username,password from user"; rs = stmt.executeQuery(sql);
while (rs.next()) { if (rs.getString(1).equals(userName) && rs.getString(2).equals(password)) { System.out.println("验证无误,可以登录!!!"); return; } }
System.out.println("用户名不存在或密码错误...."); // 考虑如修改代码使能够判断用户名不存在还是密码输入错误 } catch (SQLException e) { e.printStackTrace(); } finally { try { rs.close(); stmt.close(); con.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
public Login(boolean userPreparedStatement) { // getInfo(); userName = "root"; password = "123";
Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null;
try { con = DriverManager.getConnection("jdbc:mysql://localhost/loginDb", "root", "admin"); pstmt = con .prepareStatement("select * from user where username = ? and password = ?");
pstmt.setString(1, userName); pstmt.setString(2, password);
rs = pstmt.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
while (rs.next()) { // 调试代码 if (rsmd != null) { for (int i = 1; i <= rsmd.getColumnCount(); i++) { System.out.print(rsmd.getColumnName(i) + "\t" + rs.getString(i) + "\t"); } System.out.println(""); } } // 验证用户名密码 rs.beforeFirst(); while (rs.next()) { System.out.println("验证无误,可以登录!!!"); return; }
System.out.println("用户名不存在或密码错误...."); // 考虑如修改代码使能够判断用户名不存在还是密码输入错误 } catch (SQLException e) { e.printStackTrace(); } finally { try { rs.close(); pstmt.close(); con.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
public void getInfo() { Scanner s = new Scanner(System.in); System.out.println("请输入用户名:"); userName = s.nextLine().trim(); System.out.println("请输入密码:"); password = s.nextLine().trim(); }
public static void main(String[] args) { // new Login(); new Login(true); } } |