简化书写:注册驱动、获取连接对象、释放资源等等。
需要抽取的代码
- 加载sql配置文件、注册驱动:静态代码块(因为只需加载一次即可)
- 获取连接对象:抽取为一个方法
- 释放资源:抽取为一个方法
需求
- 在获取连接对象时,不想传递参数(麻烦),还得保证工具类的通用性。
conn = DriverManager.getConnection("jdbc:mysql:///db2", "root", "root");
思路
使用配置文件
jdbc.properties
url=
user=
password=
driver=
代码实现
package cn.luis.demo3.util;
import jdk.jfr.Description;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.Properties;
/**
* @ClassName JDBCUtils
* @Description JDBC工具类
* @Author L
* @Date 2020.01.18 11:45
* @Version 1.0
* @Remark 工具类一般都是静态的,方便调用
**/
public class JDBCUtils {
private static String url;
private static String user;
private static String password;
private static String driver;
/**
* @Author Lius
* @Description 静态代码块
* @Date 12:22 2020.01.18
* @Param
* @Return
* @Tip 只需读取一次即可拿到这些值,
**/
static {
// 读取资源文件,获取值
try {
// 1.创建Properties集合类
Properties pro = new Properties();
// 2.加载文件
// 2.1(动态)获取src路径下的文件的方式:Classloader 类加载器
ClassLoader classLoader = JDBCUtils.class.getClassLoader();
// 资源定位
URL resource = classLoader.getResource("jdbc.properties");
// 绝对路径
String path = resource.getPath();
// System.out.println(path);
// 2.2
pro.load(new FileReader(path));
// 3.获取属性,赋值
url = pro.getProperty("url");
user = pro.getProperty("user");
password = pro.getProperty("password");
driver = pro.getProperty("driver");
// 4.注册驱动
Class.forName(driver);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* @Author Lius
* @Description 获取连接
* @Date 11:47 2020.01.18
* @Param []
* @Return java.sql.Connection 返回连接对象
**/
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url,user,password);
}
/**
* @Author Lius
* @Description 释放资源(增删改)
* @Date 11:51 2020.01.18
* @Param [stmt, conn]
* @Return void
**/
public static void close(Statement stmt, Connection conn) {
if(stmt != null) {
// 注意:stmt、和conn最好不要写在一个try里面关闭,若stmt报错,conn无法关闭!
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* @Author Lius
* @Description 释放资源(查询时)
* @Date 11:51 2020.01.18
* @Param [stmt, conn]
* @Return void
**/
public static void close(ResultSet rs, Statement stmt, Connection conn) {
if(rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
演示JDBC工具类:
package cn.luis.demo1.jdbc;
import cn.luis.demo2.domain.Emp;
import cn.luis.demo3.util.JDBCUtils;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
/**
* @Description 定义一个方法
* @Author L
* @Date 2020.01.18 10:34
* @Version 1.0
* @Remark
**/
public class JDBCDemo10 {
public static void main(String[] args) {
List<Emp> list = new JDBCDemo10().findALL();
System.out.println(list.size());
for (Emp emp : list) {
System.out.println(emp);
}
}
/**
* @Author Lius
* @Description 演示JDBC工具类 数据库是:db2
* @Date 10:36 2020.01.18
* @Param []
* @Return java.util.List<cn.luis.demo2.domain.Emp>
**/
public List<Emp> findALL() {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
List<Emp> list = null;
try {
// 1.注册驱动
// 2.获取连接【使用JDBCUtil工具类】
conn = JDBCUtils.getConnection();
// 3.定义sql
String sql = "select * from emp";
// 4.获取执行sql对象
stmt = conn.createStatement();
// 5.执行sql语句
rs = stmt.executeQuery(sql);
// 6.遍历结果集,封装对象,装载集合
// 创建emp对象
Emp emp = null;
list = new ArrayList<>();
while (rs.next()) {
// 6.处理结果("id"):要和数据库中的名称相同!!!
int id = rs.getInt("id");
String ename = rs.getString("ename");
int job_id = rs.getInt("job_id");
int mgr = rs.getInt("mgr");
Date joindate = rs.getDate("joindate");
double salary = rs.getDouble("salary");
double bonus = rs.getDouble("bonus");
int dept_id = rs.getInt("dept_id");
// 创建emp对象
emp= new Emp();
emp.setId(id);
emp.setEname(ename);
emp.setJpb_id(job_id);
emp.setMgr(mgr);
emp.setJoindate(joindate);
emp.setSalary(salary);
emp.setBonus(bonus);
emp.setDept_id(dept_id);
// 装载集合
list.add(emp);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
JDBCUtils.close(rs,stmt,conn);
}
return list;
}
}
结果:
14
Emp{id=1001, ename='孙悟空',... salary=8000.0, bonus=0.0, dept_id=20}
...
Emp{id=1014, ename='关羽',...salary=13000.0, bonus=0.0, dept_id=10}
案例:使用JDBCUtil工具类模拟登陆功能
需求
-
通过键盘录入用户名和密码
-
判断用户是否登录成功
如果这个sql有查询结果,则成功,反之,则失败
select * from user where username = "" and password = "";
- 创建数据库表 user
CREATE TABLE USER(
id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(32),
PASSWORD VARCHAR(32)
);
INSERT INTO USER VALUES(NULL,'zhangsan','123');
INSERT INTO USER VALUES(NULL,'lisi','234');
代码实现
package cn.luis.demo1.jdbc;
import cn.luis.demo2.domain.Emp;
import cn.luis.demo3.util.JDBCUtils;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
* @Description 定义一个方法
* @Author L
* @Date 2020.01.18 10:34
* @Version 1.0
* @Remark
**/
public class JDBCDemo11 {
public static void main(String[] args) {
// 1.键盘录入
Scanner sc = new Scanner(System.in);
System.out.print("输入用户名:");
String username = sc.next();
System.out.print("输入密码:");
String password = sc.next();
// 2.调用方法
boolean flag = new JDBCDemo11().login(username, password);
// 3.判断结果
if(flag) {
System.out.println("登陆成功!");
} else {
System.out.println("用户名或密码错误!");
}
}
/**
* @Author Lius
* @Description 练习,登录方法
* @Date 10:36 2020.01.18
* @Param []
* @Return java.util.List<cn.luis.demo2.domain.Emp>
**/
public boolean login(String username, String password) {
if(username == null || password == null) {
return false;
}
// 连接数据库
// 1.获取连接
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// 1.获取连接
conn = JDBCUtils.getConnection();
// 2.定义sql
String sql = "select * from user where username = '"+ username +"' and password = '"+ password +"'";
// 3.获取执行sql对象
stmt = conn.createStatement();
// 4.执行sql语句
rs = stmt.executeQuery(sql);
// 5.判断
/*if(rs.next()) { // 如果有下一行,则返回true
return true;
} else {
return false;
}*/
return rs.next(); // 如果有下一行,则返回true
} catch (SQLException e) {
e.printStackTrace();
} finally {
JDBCUtils.close(rs,stmt,conn);
}
return false;
}
}
结果:
输入用户名:zhangsan
输入密码:123
Sat Jan 18 13:35:28 CST 2020 WARN: ...
登陆成功!