发表于: 2017-08-16 15:28:21
1 1070
今天完成的事情:
使用C3P0连接池 测试不关闭连接会出现的问题
昨天使用的Spring框架 直接在xml文件里 设置数据源 不方便测试
今天改为直接写在java文件夹下新建了一个包c3p0
写了一个类来设置C3P0 直接在主函数进行测试 具体如下 记得要在pom文件里添加所需依赖
package c3p0;
import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import javax.xml.transform.Result;
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 = "123123";
static final String jdbcurl="jdbc:mysql://localhost:3306/student?useUnicode=true&characterEncoding=UTF-8&useSSL=true";
static {
dbPool = new DBPool();
}
public DBPool() {
try {
dataSource = new ComboPooledDataSource();
dataSource.setUser("root");
dataSource.setPassword("123123");
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/student?useUnicode=true&characterEncoding=UTF-8&useSSL=true");
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;
ResultSet result=null;try {
for (int i = 0; i < 300; i++) {
System.out.println("---di" + (i + 1) + "ci");
con = DBPool.getInstance().getConnection();
stmt = con.createStatement();
sql = "select * from student";
result = stmt.executeQuery(sql);
while(result.next()){
System.out.println(result.getString(1)+"\t"+result.getString(2));
}
if(stmt !=null) stmt.close();
if (con != null) con.close();
if(result !=null) result.close();
// System.out.println(userMapper.selectUser(u));
}
} catch (Exception e) {
e.printStackTrace();
上边的设置很简单 数据源的通用设置 然后写了个for循环 跟jdbc基本一致 创建对象 获得sql语句 执行
然后关闭 我们跑一下
把关闭的语句注释掉 跑一下
可以看到 运行到10次 就无法继续运行了 我猜测是因为数据库连接池数量设置为10的原因
然后今天临时通知我明天讲小课堂 打算讲一下maven的相关知识 复习了一下
然后做了ppt 提前练习了一遍
晚上看了看Spring mvc 的内容 相关基础知识 看得很晕
明天计划的事情:重写spring 融合mybatis的代码
尝试 Spring mvc
下载使用tomcat
遇到的问题:写数据路连接池测试的时候 犯了很多错误
开始写了catch 没写e.printStackTrace导致运行后异常 但是没有日志被打印
后来写上去后顺利打印日志报错 查询方法不能用executeUpdata
改用了方法 又把关闭语句写在了for方法外面。。。
收获:理解了数据库连接池的意义 必须要在最后关闭
看了rest的概念 就记住一句url定位资源 http描述操作
看了spring mvc主要是由DispatcherSerlet、处理器映射、处理器(控制器)、视图解析器、视图组成。有两个核心
处理器映射:选择使用哪个处理器来处理请求
视图解析器 :选择结果如何渲染
评论