本博客用于自己记录学习整理知识
首先需要导入jar包
commons-dbcp-1.4.jar、commons-pool-1.5.5.jar
在src文件下创建 dbcpconfig.properties 文件用于读取数据库
// dbcpconfig.properties 文件代码
driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/jdbcstudy?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&uesSSL=false
username=root
password=root
java工具类实现(简化连接数据库的过程)
private static DataSource dataSource=null;
static {
try{
InputStream resourceAsStream = JdbcUtils_dbcp.class.getClassLoader().getResourceAsStream("dbcpconfig.properties");
Properties properties = new Properties();
properties.load(resourceAsStream);
//创建数据源 工厂模式--> 创建对象
dataSource = BasicDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
}
//获取连接
public static Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
//释放资源
public static void release(Connection conn, Statement st, ResultSet rs){
if(rs!=null){
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(st!=null){
try {
st.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
对数据库的插入操作测试
```java
public static void main(String[] args) {
Connection connection = null;
PreparedStatement statement = null;
try {
connection = JdbcUtils_dbcp.getConnection();
String sql = "INSERT INTO users(`id`,`NAME`,`PASSWORD`,`email`,`birthday`) VALUES(?,?,?,?,?)";
statement = connection.prepareStatement(sql);
//手动给参数赋值
statement.setInt(1,4);
statement.setString(2,"zhenzhen");
statement.setString(3,"132321456");
statement.setString(4,"2267253192@qq.com");
statement.setDate(5,new java.sql.Date(new Date().getTime()));
int i = statement.executeUpdate();
if(i>0){
System.out.println("插入成功~");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
JdbcUtils_dbcp.release(connection,statement,null);
}
}