发表于: 2017-12-05 23:21:06
1 758
今天完成的事:
不关闭连接池,向连接池插入1000个循环数据;
遇到的困难:
报错:java.sql.SQLException: The server time zone value '�й���ʱ��' is unrecognized or represents more than one time zone.
解决:驱动版本高,写url时应该加上后缀
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC");
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.3</version>
</dependency>
明天计划:
测试一下连接DB中断后TryCatch是否能正常处理。
c3p0从配置文件获取参数,从xml设置参数的两种方式。
收获:
数据库连接池原理图:
数据库连接池负责分配管理和释放数据库连接,允许重复使用现有的连接而不是每次新建一个。相当于程序和数据库之间的缓冲地带,预先在缓冲池中放入一定数量的连接,当需要建立数据库连接时,只需从“缓冲池”中取出一个,使用完毕之后再放回去。程序的关闭连接是中断和连接池中连接,而不是直接和数据库的连接。
向数据库插入数据代码:
public class DBPool {
private static DBPool dbPool;
private ComboPooledDataSource dataSource;
static String sql;
static final String name = "com.mysql.jdbc.Driver";
static final String user = "root";
static final String password = "123456";
static final String jdbcurl = "jdbc:mysql://localhost:3306/test?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";
static {
dbPool = new DBPool();
}
public DBPool() {
try {
dataSource = new ComboPooledDataSource();
dataSource.setUser("root");
dataSource.setPassword("123456");
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC");
dataSource.setDriverClass("com.mysql.jdbc.Driver");
dataSource.setMinPoolSize(1);
dataSource.setMaxPoolSize(10);
dataSource.setMaxStatements(50);
dataSource.setMaxIdleTime(60);
System.out.println("success");
} catch (PropertyVetoException e) {
throw new RuntimeException(e);
}
}
public final static DBPool getInstance() {
return dbPool;
}
public final Connection getConnection() {
try {
return dataSource.getConnection();
} catch (SQLException e) {
throw new RuntimeException("无法从数据源获取连接 ", e);
}
}
public static void main(String[] args) throws SQLException {
Connection con = null;
Statement stmt = null;
try {
int i;
for (i=0;i<1000;i++) {
con = DBPool.getInstance().getConnection();
sql = "insert into students(name,age) values (?,?)";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, "sss");
ps.setString(2, "2");
ps.execute();
if (ps != null) ps.close();
if (con != null) con.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
每次插入后不关闭连接:
之后出现连接不够的信息:WARN: Establishing SSL connection without server's identity verification is not recommended.
不关闭连接,因为设置的连接池最大连接数量是10,刚好用完所以停止插入数据。
dataSource.setMaxPoolSize(10);
禅道:
http://task.ptteng.com/zentao/my-task.html
评论