一代码连接:
1.pom.xml
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
2.Test
@Test
public void dbcp1(){
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://127.0.0.1/work?useSSL=false&serverTimezone=UTC");
dataSource.setUsername("root");
dataSource.setPassword("123456");
Connection conn = null;
PreparedStatement pst= null;
ResultSet rs= null;
try {
conn = dataSource.getConnection();
String sql = "select * from transaction1";
pst=conn.prepareStatement(sql);
rs = pst.executeQuery();
while (rs.next()){
int id = rs.getInt(1);
int money = rs.getInt(2);
System.out.println("id :"+id +" money:"+money);
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
JDBCUtils.close(rs,pst,conn);
}
}
二使用配置文件
代码:
1.dbcpconfig.properties
#连接设置
driverClass=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://127.0.0.1/work?useSSL=false&serverTimezone=UTC
username=root
password=123456
#<!--初始化连接-->
initialSize=10
#最大连接数量
maxActive=50
#<!--最大空闲连接-->
maxIdle=20
#<!--最小空闲连接-->
minIdle=5
#<!--超时等待时间以毫秒为单位 6000毫秒/1000 等于60秒-->
maxWait=60000
#JDBC驱动建立连接时附带的连接属性的格式必须为这样:[属性名=property;]
#注意:"user"与"password"两个属性会被明确地传递,因此这里不需要包含他们。
connectionProperties=useUnicode=true;characterEncoding=utf8
#指定由连接池所创建的连接自动提交(auto-commit)状态
defaultAutoCommit=true
#driver default 指定由连接池所创建的连接的只读(read-only)状态。
#如果没有设置该值,则“setReadOnly”方法将不被调用。(某些驱动并不支持只读模式,如:Informix)
defaultReadOnly=
#driver default 指定由连接池所创建的连接的事务级别(TransactionIsolation)。
#可用值为下列之一:(详情可见javadoc。)NONE,READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE
defaultTransactionIsolation=REPEATABLE_READ
2.Test
public class DBCPProperties {
@Test
public void tes(){
Connection conn = null;
PreparedStatement pst= null;
ResultSet rs= null;
try {
BasicDataSourceFactory factory = new BasicDataSourceFactory ();
Properties properties = new Properties();
InputStream is = new FileInputStream(
"src//main//resources//dbcpconfig.properties");
properties.load(is);
DataSource dataSource = factory.createDataSource(properties);
///
conn = dataSource.getConnection();
String sql = "select * from transaction1";
pst=conn.prepareStatement(sql);
rs = pst.executeQuery();
while (rs.next()){
int id = rs.getInt(1);
int money = rs.getInt(2);
System.out.println("id :"+id +" money:"+money);
}
} catch (SQLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.close(rs,pst,conn);
}
}
}