JDBC工具类
为什么要写JDBC工具类?
在学习jdbc工具类之前,你会很清晰的发现,大量重复的代码,既浪费时间又浪费资源,所以通过一个工具类可以轻松的解决代码书写时间!
工具类的作用
- 实现注册驱动 和 连接对象的获取
- 释放资源
所有操作前需要导包
需要导入包:mysql-connector-java-5.1.20-bin.jar
注意:根据自己电脑软件情况来导入包,有的需要的是8.0的版本,作者需要的是5.1的版本,这些都可以在网上搜索下载。
https://mvnrepository.com/artifact/mysql/mysql-connector-java
完整代码实现
JDBCUtils.java
public class JDBCUtils {
private static String url;
private static String user;
private static String password;
private static String driver;
static {
try {
//1. 创建properties集合类
Properties pro = new Properties();
//2. 获取文件
URL res = JDBCUtils.class.getClassLoader().getResource("jdbc.properties");
String path = res.getPath();
//3. 加载文件
pro.load(new FileReader(path));
//4. 获取数据,赋值
url = pro.getProperty("url");
user = pro.getProperty("user");
password = pro.getProperty("password");
driver = pro.getProperty("driver");
//5. 注册驱动
Class.forName(driver);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取连接
*/
public static Connection getConnection() throws Exception{
return DriverManager.getConnection(url,user,password);
}
/**
* 释放资源
* @param stmt
* @param conn
*/
public static void close(Statement stmt, Connection conn){
close(null,stmt,conn);
}
/**
* 释放资源
* @param res
* @param stmt
* @param conn
*/
public static void close(ResultSet res, Statement stmt, Connection conn) {
if (res != null) {
try {
res.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.properties:
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/dbl
/*
如果导入的包是8以上的版本,是需要设置编码和时区的,直接在数据库名后加上
"?useUnicode=true&characterEncoding=utf-8&useSSL=false"
例如:url=jdbc:mysql://localhost:3306/dbl?useUnicode=true&characterEncoding=utf-8&useSSL=false
*/
user=root
password=123456
这样一个JDBC工具类就完成了,之后的调用如下所示:
Connection con = JDBCUtils.getConnection();
留个赞再走吧!