目的
- 代码复用
- 灵活性
提高程序的灵活性,不能将使用的数据库信息写死,如果使用的是另外一种数据库就需要修改源代码.当多次执行增改的时候,直接调用方法.
表结构
工具类
配置文件:
记得做实验的时候,需要加入时区,ssl,后面的两个可用可不用,没有时区会出异常哟.
package cn.xiao.utils;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class JdbcUtils {
private static Properties properties = new Properties();
private static String url;
private static String user;
private static String password;
//获取驱动(从配置文件中)
static {
InputStream inputStream = JdbcUtils.class.getClassLoader().getResourceAsStream("setting.propreties");
try {
properties.load(inputStream);
String driver = properties.getProperty("driver");
url = properties.getProperty("url");
user = properties.getProperty("user");
password = properties.getProperty("password");
Class.forName(driver);
} catch (IOException | ClassNotFoundException e) {
throw new ExceptionInInitializerError(e);
}
}
//获取连接
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url,user,password);
}
//释放资源
public static void release(Connection connection, Statement statement, ResultSet resultSet) {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
这里我们使用静态代码块来加载驱动.驱动只需要加载一次即可,放在静态代码块中最适宜.注意:
这个properties文件需要放在src目录下.不然无法找到这个文件,会显示类加载不出来.
package cn.xiao.utils;
import org.junit.Test;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Demo2 {
@Test
public void add() {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
connection = JdbcUtils.getConnection();
statement = connection.createStatement();
String sql = "insert into users(id,name,password,email,birthday) values('5','a','123','[email protected]','1997-1-31')";
int num = statement.executeUpdate(sql);
if (num > 0) {
System.out.println("执行成功");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtils.release(connection, statement, resultSet);
}
}
}
之后就可以随心所欲地写语句了
坑记录
我遇到的坑就是测试的时候无法初始化工具类,但是归根究底 一步一步拍错之后,是文件没有放在src目录下,导致输入流找不到.如果你也遇到了,可以参照参照哟