JDBC工具类实现登陆验证-Java(新手)
JDBC工具类:
1 package cn.chuang.JdbcDome; 2 3 import java.sql.*; 4 5 public class JdbcUtilss { 6 private static final String user = "root"; 7 private static final String r = "root"; 8 private static final String p = "root"; 9 private static final String url = "jdbc:mysql:///semployee"; 10 private static final String DRIVER = "com.mysql.jdbc.Driver"; 11 //注册驱动。 12 static{ 13 try { 14 Class.forName(DRIVER); 15 } catch (ClassNotFoundException e) { 16 e.printStackTrace(); 17 } 18 } 19 //得到数据库链接。 20 public static Connection getConnection() throws Exception { 21 return DriverManager.getConnection(url,r,p); 22 } 23 24 //关闭链接,执行打开的资源。 25 public static void close(Connection conn,Statement stmt){ 26 if (stmt!=null){ 27 try { 28 stmt.close(); 29 } catch (Exception e) { 30 e.printStackTrace(); 31 } 32 } 33 if (conn!=null){ 34 try { 35 conn.close(); 36 } catch (Exception e) { 37 e.printStackTrace(); 38 } 39 } 40 } 41 //关闭所有打开的资源。 42 public static void close(Connection conn, Statement stmt, ResultSet rs){ 43 if (stmt!=null){ 44 try { 45 stmt.close(); 46 } catch (Exception e) { 47 e.printStackTrace(); 48 } 49 }if (conn!=null){ 50 try { 51 conn.close(); 52 } catch (Exception e) { 53 e.printStackTrace(); 54 } 55 } 56 if (rs!=null){ 57 try { 58 rs.close(); 59 } catch (Exception e) { 60 e.printStackTrace(); 61 } 62 } 63 } 64 65 }
利用JDBC工具类实现登陆验证:
1 package cn.chuang.JdbcDome; 2 3 import java.sql.Connection; 4 import java.sql.PreparedStatement; 5 import java.sql.ResultSet; 6 import java.sql.Statement; 7 import java.util.Scanner; 8 9 public class JdbcUtilsUser { 10 public static void main(String[] args){ 11 Scanner sc = new Scanner(System.in); 12 System.out.println("请输入用户名"); 13 String name = sc.nextLine(); 14 15 System.out.println("请您输入密码"); 16 String password = sc.nextLine(); 17 login(name,password); 18 } 19 public static void login(String name,String password){ 20 Connection conn = null; 21 PreparedStatement pre=null; 22 ResultSet rs = null; 23 24 try { 25 conn = JdbcUtilss.getConnection(); 26 String sql = "select * from zh where uname = '"+name+"' and upd = '"+password+"'" ; 27 pre = conn.prepareStatement(sql); 28 rs = pre.executeQuery(); 29 System.out.println(sql); 30 if (rs.next()){ 31 System.out.println("登陆成功,欢迎您"+name); 32 }else{ 33 System.out.println("登录失败"); 34 } 35 } catch (Exception e) { 36 e.printStackTrace(); 37 } 38 finally { 39 JdbcUtilss.close(conn,pre,rs); 40 } 41 } 42 }