最近总是用到数据库,真是烦,各种连接池和操作,jdbc,dbcp,c3p0。
为了避免以后忘记,还是记下来吧。
JDBC数据库
建表
USE test;
CREATE TABLE user(
name VARCHAR(10) PRIMARY KEY ,
YEAR INT
);
传统方式
需要的包
mysql-connector-java-6…0.3jar 根据需要选择版本
贴个DBUtil吧
package com.dao.enterties;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
/**
* Created by Administrator on 2018/10/1.
*/
public class DBUtil {
private static Connection conn = null;
private static Statement stat = null;
public static Statement getStat() {
if (stat == null) {
try {
Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/购物车系统?" +
"useUnicode=true&characterEncoding=UTF-8&serverTimez" +
"one=GMT", "root", "root");
stat = conn.createStatement();
} catch (InstantiationException e) {
e.printStackTrace();
return null;
} catch (IllegalAccessException e) {
e.printStackTrace();
return null;
} catch (ClassNotFoundException e) {
e.printStackTrace();
return null;
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
return stat;
}
public static boolean close() {
try {
if (conn != null)
conn.close();
if (stat != null)
stat.close();
} catch (SQLException e) {
e.printStackTrace();
return false;
}
return true;
}
}
主要是Statement来实现数据库操作,这里如果是多线程的话还得在
初始化加上双重检测锁实现同步。
还有,加上这句useUnicode=true&characterEncoding=UTF-8&serverTimez" +
"one=GMT"是为了修改mysql的编码,还有修改server的时间
不然会出现错误比如
org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC
Connection; nested exception is org.apache.commons.dbcp.SQLNestedException:
Cannot create PoolableConnectionFactory (The server time zone value 'Öйú±ê׼ʱ¼ä'
is unrecognized or represents more than one time zone. You must configure either the
server or JDBC driver (via the serverTimezone configuration property) to use a more
specifc time zone value if you want to utilize time zone support.)
at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(
DataSourceUtils.java:80)
好像是因为数据库设置问题吧,还搞bu懂,有大佬知道的话请指教
还有,最新版的mysql驱动改了,的换成com.mysql.cj.jdbc.Driver,不然
会出错。
现在知道是什么问题了,mysql的时区设置不是当前的时区,可以设置
my.ini里的参数,不过很麻烦,可以在mysql命令行运行
SET TIME_ZONE =’+8:00’;设置为北京时间。
BasicDataSource和JdbcTemplate
实际开发中“获得连接”或“释放资源”是非常消耗系统资源的两个过程,为了解决此类性能问题,
*通常情况我们采用连接池技术,来共享连接Connection。这样我们就不需要每次都创建连接、释放连接了,这些操作都交给了连接池
DBCP也是一个开源的连接池,是Apache Common成员之一,在企业开发中也比较常见,tomcat内置的连接池。
使用DBCP连接池,需要导入两个包
commons-dbcp
commons-pool
Java中提供了一个连接池的规则接口 :
DataSource : 它是java中提供的连接池,作为 DriverManager 工具的替代项。在DBCP包中提供了DataSource接口的实现类,
我们要用的具体的连接池 BasicDataSource类
原文:https://blog.csdn.net/alexzt/article/details/80309433?utm_source=copy
package aop整合dbcp;
import org.apache.commons.dbcp.BasicDataSource;
import org.junit.Test;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import javax.sql.RowSet;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
/**
* Created by Administrator on 2018/10/10.
* https://www.cnblogs.com/yysbolg/p/6699484.html
*/
public class testApi {
@Test
public void testDemo1() throws SQLException {
BasicDataSource dataSource=new BasicDataSource();
dataSource.setUrl("jdbc:mysql://localhost:3306/test" +
"?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT");
//设置数据库编码为utf-8以及服务器时间,不然会出错
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUsername("root");
dataSource.setPassword("root");
//创建数据库模板
JdbcTemplate template=new JdbcTemplate();
template.setDataSource(dataSource);
String sql="insert into user values(?,?);";
// template.update(sql,"张三",21);
List<User> user=template.query("SELECT *FROM user WHERE name=?", new RowMapper<User>() {
@Override
public User mapRow(ResultSet resultSet, int i) throws SQLException {
User user=new User();
user.setName(resultSet.getString("name"));
user.setYear(resultSet.getInt("year"));
return user;
}
},"张三");
String name=template.queryForObject("select name from user where name=\'李四\'",String.class);
System.out.println(user.get(0));
System.out.println(name);
// template.update("SELECT *FROM user");
//2、设置连接是否默认自动提交
dataSource.setDefaultAutoCommit(true);
//3、设置初始后连接数
dataSource.setInitialSize(3);
//4、设置最大的连接数
dataSource.setMaxActive(5);
//5、设置空闲等待时间,获取连接后没有操作开始计时,到达时间后没有操作回收链接
dataSource.setMaxIdle(3000);
//三、测试获取连接
Connection c1 = dataSource.getConnection();
System.out.println("获取连接地址:"+c1.getClass());
}
}
Dbcp连接池
DBCP简介
DBCP(DataBase connection pool)数据库连接池是 apache 上的一个Java连接池项目。DBCP通过连接池预先同数据库建立一些连接放在内存中(即连接池中),应用程序需要建立数据库连接时直接到从接池中申请一个连接使用,用完后由连接池回收该连接,从而达到连接复用,减少资源消耗的目的。
DBCP所依赖的jar包(以下例子基于如下jar包版本)
commons-dbcp2-2.1.1.jar commons-logging-1.2.jar commonspool2-2.4.2.jar
需要使用配置文件才能使用basicdatasource
########DBCP配置文件##########
#驱动名
driverClassName=com.mysql.cj.jdbc.Driver
#url
url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true\&characterEncoding=utf8&serverTimezone=GMT
#用户名
username=root
#密码
password=root
#初试连接数
initialSize=30
#最大活跃数
maxTotal=30
#最大idle数
maxIdle=10
#最小idle数
minIdle=5
#最长等待时间(毫秒)
maxWaitMillis=1000
#程序中的连接不使用后是否被连接池回收(该版本要使用removeAbandonedOnMaintenance和removeAbandonedOnBorrow)
#removeAbandoned=true
removeAbandonedOnMaintenance=true
removeAbandonedOnBorrow=true
#连接在所指定的秒数内未使用才会被删除(秒)(为配合测试程序才配置为1秒)
removeAbandonedTimeout=1
测试一下获取Statement和Connection
package aop整合dbcp;
import org.apache.commons.dbcp.BasicDataSourceFactory;
import org.junit.Test;
import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
/**
* Created by Administrator on 2018/10/10.
*/
public class DbcpTest {
private static Properties properties = new Properties();
private static DataSource dataSource;
@Test
public void testDemo() throws Exception {
//加载DBCP配置文件
try{
FileInputStream is =new FileInputStream("C:/Users/Administrator.PC-201807161523/eclipse-workspace/firstSpring/src/aop整合dbcp/dbcp.properties");
properties.load(is);
}catch(IOException e){
e.printStackTrace();
}
try{
dataSource = BasicDataSourceFactory.createDataSource(properties);
}catch(Exception e){
e.printStackTrace();
}
Connection con=dataSource.getConnection();
Statement sta=con.createStatement();
}
}