java 应用程序登录功能的实现
package s; import java.sql.*; import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class test01 { public static void main(String[] args) { /*初始化界面*/ Map<String,String>userinfo=initUI(); /*验证登陆密码账户*/ boolean i=login(userinfo); System.out.println(i? "登陆成功":"登陆失败"); } private static boolean login(Map<String, String> userinfo) { Connection conn=null; Statement stmt=null; ResultSet rs=null; try { Class.forName("com.mysql.jdbc.Driver"); conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/JDBCtest03","root","zber1574"); stmt=conn.createStatement(); String sql="select * from test where user='"+userinfo.get("user")+"'and password='"+userinfo.get("password")+"'"; rs=stmt.executeQuery(sql); if(rs.next()) { return true; } } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); }finally { if(rs!=null) { try { rs.close(); } catch (SQLException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } } if(stmt!=null) { try { stmt.close(); } catch (SQLException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } } if(conn!=null) { try { conn.close(); } catch (SQLException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } } } return false; } private static Map<String, String> initUI() { Scanner sc=new Scanner(System.in); System.out.println("请输入账户:"); String user=sc.next(); System.out.println("请输入密码:"); String password=sc.next(); Map<String,String>userlogin=new HashMap<>(); userlogin.put("user", user); userlogin.put("password", password); return userlogin; } }
用Map类创建账号与密码,连接数据库判断输入的密码是否正确,若正确输出登陆成功。