LoginUser.java
package com.yikuan.Login; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Scanner; import cn.tedu.util.JDBCUtils; /** * 这个类用来模拟用户登录 * @author Administrator * */ public class LoginUser { //1.main方法,提示用户输入 public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("请输入用户名:"); String name = sc.nextLine(); System.out.println("请输入密码:"); String pwd = sc.nextLine(); //去user表根据用户输入的用户名和密码查询数据,利用jdbc技术 login(name,pwd); } private static void login(String name, String pwd) { Connection conn = null; PreparedStatement ps = null; //对象PreparedStatement有预编译的过程 ResultSet rs = null; try { //1.注册驱动 //2.获取数据库连接 conn = JDBCUtils.getConnection(); //3.获取传输器 // String sql = "select * from user where username='"+name+"' and password='"+pwd+"' "; String sql = "select * from user where username=? and password=?"; //sql中包含?的叫做sql骨架,?叫做占位符; ps = conn.prepareStatement(sql); //给sql语句设置参数 ps.setString(1, name); ps.setString(2, pwd); //4.执行sql rs = ps.executeQuery(); //5.遍历结果集 /* * 如果rs有值,就可以登录成功,反则登录失败 */ if(rs.next()){ System.out.println("恭喜你!登录成功!"); }else{ System.out.println("您输入的用户名或密码错误!"); } //6.释放资源` } catch (SQLException e) { e.printStackTrace(); } finally { JDBCUtils.close(rs, ps, conn); } } }
JDBCUtils.java
package cn.yikuan.util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ResourceBundle; /** * 这个类用来提供JDBC的工具类 * @author Administrator * */ public class JDBCUtils { //1.私有化构造函数,外界无法直接创建对象 private JDBCUtils(){ } static ResourceBundle rb = null; static { //读取属性文件 rb = ResourceBundle.getBundle("jdbc"); } //2.提供公共的,静态的,getConnection方法,用来给外界提供数据库连接 public static Connection getConnection(){ try { //2.1注册驱动 Class.forName(rb.getString("driverClass")); //2.2获取数据库连接 String url = rb.getString("jdbcUrl"); String user = rb.getString("user"); String password = rb.getString("password"); Connection conn = DriverManager.getConnection(url, user, password); return conn; } catch (Exception e) { e.printStackTrace(); } return null; } //3.提供公共的,静态的,close方法,用来释放资源 public static void close(ResultSet rs,Statement st,Connection conn){ //3.1非空判断,防止空指针异常 //3.2手动置为空,保证完全释放 if(rs != null){ try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } finally { rs = null; } } if(st != null){ try { st.close(); } catch (SQLException e) { e.printStackTrace(); } finally { st = null; } } if(conn != null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } finally { conn = null; } } } }
jdbc.properties(该配置文件不可以有空格)
driverClass=com.mysql.jdbc.Driver jdbcUrl=jdbc:mysql:///jtdb user=root password=123456