JDBC工具类
目的:简化书写
分析:
-
注册驱动
-
抽取一个方法获取连接对象
- 需求:不想传递参数(麻烦),还要保证工具类的通用性。
- 解决:配置文件
package JDBC工具类; import javax.xml.transform.Result; import java.io.FileReader; import java.io.IOException; import java.net.URL; import java.sql.*; import java.util.Properties; public class Demo01 { /** * 文件的读取,只需要读取一次即可拿到这些值,可以使用静态代码块 */ private static String url; private static String user; private static String password; private static String driver; static { //读取资源文件,获取值。 //创建Proerties集合类。 try { Properties pro = new Properties(); //获取src路径下的文件的方式-->ClassLoader 类加载器 ClassLoader classLoader = Demo01.class.getClassLoader(); URL res = classLoader.getResource("jdbc.properties"); String path = res.getPath(); System.out.println(path); pro.load(new FileReader(path)); url = pro.getProperty("url"); user = pro.getProperty("user"); password = pro.getProperty("password"); driver = pro.getProperty("driver"); Class.forName(driver); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } /** *获取连接 * @return 连接对象 */ public static Connection getConnection() throws SQLException { return DriverManager.getConnection(url,user,password); } /** *释放资源 * @param rs * @param stmt * @param conn */ public static void close(ResultSet rs,Statement stmt, Connection conn){ if(rs != null){ try { rs.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } if(stmt != null){ try { stmt.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } if(conn != null){ try { conn.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } } }
动态获取配置文件绝对路径的方法 ClassLoader classLoader = Demo01.class.getClassLoader(); URL res = classLoader.getResource("jdbc.properties"); String path = res.getPath(); pro.load(new FileReader(path));
-
抽取一个方法释放资源
练习:
需求:
- 通过键盘录入用户名和密码
- 判断用户是否登录成功
package JDBC工具类;
import java.sql.*;
import java.util.Scanner;
public class lianxi {
public static void main(String[] args) throws SQLException {
//键盘录入,接受用户名和密码
Scanner sc = new Scanner(System.in);
System.out.println("请输入用户名");
String username = sc.nextLine();
System.out.println("请输入密码");
String password = sc.nextLine();
//调用方法
boolean flag = new lianxi().login(username,password);
//判断结果
if (flag){
//登录成功
System.out.println("登录成功");
} else {
System.out.println("登录失败");
}
}
/**
* 登录方法
*/
public boolean login(String username,String password) throws SQLException {
if (username == null && password == null){
return false;
}
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
conn = Demo01.getConnection();
String sql = "select * from USER where username = ? and password = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1,username);
pstmt.setString(2,password);
rs = pstmt.executeQuery();
return rs.next();
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
Demo01.close(rs,pstmt,conn);
}
return false;
}
}