背景
学习数据库的使用,上次没有记录,现在都回忆不起来了,所以这次重新学的时候顺便记录下。
配置环境
win10
jdk11
idea
mysql8.0.13
DBCP连接使用
用配置文件目前我连接不来
jar包
mysql-connector-java-8.0.14
commons-pool2-2.6.0
commons-logging-1.2
commons-dbcp2-2.5.0
使用代码连接数据库
代码
import org.apache.commons.dbcp2.BasicDataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
BasicDataSource dataSource = new BasicDataSource();
/*mysql数据库的连接,参考我上篇文章*/
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/webdemo?useSSL=false&serverTimezone=UTC");
dataSource.setUsername("root");
dataSource.setPassword("root");
测试
Connection conn = dataSource.getConnection();
String sql = "INSERT INTO category VALUES('ee','ee');";
PreparedStatement preparedStatement = conn.prepareStatement(sql);
/*增删改:执行更新*/
System.out.println(preparedStatement.executeUpdate());
曾经报错
java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
解决方法:导入commons-logging.jar
C3P0的使用
jar包
c3p0-0.9.5.2
mchange-commons-java-0.2.11
mysql-connector-java-8.0.14
使用代码连接数据库
代码
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.junit.Test;
import java.sql.Connection;
import java.sql.PreparedStatement;
public class c3p0Demo {
@Test
public void c3p0Test() throws Exception {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass("com.mysql.cj.jdbc.Driver");
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/webdemo?useSSL=false&serverTimezone=UTC");
dataSource.setUser("root");
dataSource.setPassword("root");
Connection conn = dataSource.getConnection();
String sql = "INSERT INTO category VALUES('bvb','gg');";
PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.executeUpdate();
}
}
曾经报错
java.lang.NoClassDefFoundError:com.mchange.v2.ser.Indirector
解决方法:这是c3p0的一个错误信息,我们在下载 c3p0时候,zip压缩包中,有三个jar,其中一个 c3p0-x.x.x.jar,还有一个 mchange.......jar的文件,导入即可
使用配置文件连接数据库
在src文件夹下创建 c3p0-config.xml ,名字和地址都不能改
配置文件代码,注意其中的 & 要转义为&
com.mysql.cj.jdbc.Driver
jdbc:mysql://localhost:3306/webdemo?useSSL=false&serverTimezone=UTC
root
root
10
30
100
10
200
测试代码
package cn.wahll.test;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.junit.Test;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class c3p0Demo {
@Test
public void c3p0PoolTest() throws Exception {
//直接找到配置文件下的默认配置
ComboPooledDataSource dataSource = new ComboPooledDataSource();
//测试代码
Connection conn = dataSource.getConnection();
String sql = "INSERT INTO category VALUES('bsafvb','asdgg')";
PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.executeUpdate();
}
}