1. 引入相关依赖
<dependencies>
<!--引入lombok依赖-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.30</version>
</dependency>
<!--引入单元测试依赖-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!--引入mysql依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.30</version>
</dependency>
<!--引入德鲁伊得依赖-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.8</version>
</dependency>
<!--单元测试依赖-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<!-- <scope>test</scope>-->
</dependency>
</dependencies>
2. 准备工具类Util
① 使用JDBC获取properties文件
注意:
在使用jdbc编程时,编写的属性文件中最好以jdbc.xxx的方式命名
如:jdbc.username:root
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
/**
* @program: ORM
* @description: 没有使用连接池的数据库工具类
* @author:
* @create: 2024-07-01 19:56
**/
public class DButil {
private static String driverName = "";
private static String url = "";
private static String username = "";
private static String password = "";
//静态代码块
static {
try {
//读取属性文件
InputStream inputStream = ClassLoader.getSystemResourceAsStream("db.properties");
//创建属性类 用于读取属性
Properties properties = new Properties();
properties.load(inputStream);
driverName = properties.getProperty("jdbc.driverName");
url = properties.getProperty("jdbc.url");
username = properties.getProperty("jdbc.username");
password = properties.getProperty("jdbc.password");
} catch (IOException e) {
e.printStackTrace();
}
}
//获取数据库连接
public static Connection getConnection(){
Connection connection = null;
try {
Class.forName(driverName);
connection = DriverManager.getConnection(url,username,password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
//关闭所有连接
public static void closeAll(Connection connection, PreparedStatement ps, ResultSet rs){
try {
if(connection != null){
connection.close();
}
if (ps != null){
ps.close();
}
if (rs != null){
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
② 使用数据源获取properties文件
注意:
在使用数据源的情况下,例如本次使用的德鲁伊数据源,在编写属性文件时,就不需要再加 jdbc. 了
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.