package com.tr.jdbc;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.apache.commons.dbcp2.BasicDataSource;
public class CollectionFactory {
private final static String dbDriver = "com.mysql.jdbc.Driver";
private final static String dbUrl="jdbc:mysql://localhost:3306/xtest?useUnicode=true&characterEncoding=UTF-8" ;
private final static String dbUser="root";
private final static String dbpwd="root";
private static BasicDataSource dataSource;
//创建dbcp的简单数据源并初始化相关属性
static{
dataSource = new BasicDataSource();
dataSource.setDriverClassName(dbDriver);
dataSource.setUrl(dbUrl);
dataSource.setUsername(dbUser);
dataSource.setPassword(dbpwd);
//指定数据库连接池初始化连接数
dataSource.setInitialSize(10);
//设定同时向数据库申请的最大连接数
dataSource.setMaxTotal(50);
//设置连接池中保持的最少连接数量
dataSource.setMinIdle(5);
//其他属相...参考Apache的公开文档
}
//创建数据库连接对象--并且多线程并发处理(注意Connection导的是Java.sql的包)
public static synchronized Connection creatConnection(){
Connection conn = null;
if(dataSource!=null&&!dataSource.isClosed()){
try {
conn = dataSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
}
return conn;
}
public static void main(String[] args) {
String sql = "select * from s_t_user";
Connection conn = creatConnection();
Statement statement = null;
ResultSet resultSet = null;
try {
statement = conn.createStatement();
resultSet= statement.executeQuery(sql);
int row = 0;
while(resultSet.next()){
row++;
System.out.println("记录行"+row+"col2:"+resultSet.getString(2));
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
if (conn!=null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
一定要注意不能导错包,我刚才就是因为BasicDataSource的包导错了,写成了import org.apache.tomcat.dbcp.dbcp2.BasicDataSource;应该是
import org.apache.commons.dbcp2.BasicDataSource;
而一直报这样的错误