<?xml version="1.0" encoding="UTF-8"?>
<!-- 需要导入c3p0驱动jar包和mysql驱动jar包 -->
<!-- c3p0-config.xml配置文件放在src包下 -->
<c3p0-config>
<named-config name="mysqlConnection">
<property name="user">root</property>
<property name="password"></property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/test</property>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="initialPoolSize">20</property>
<property name="maxPoolSize">25</property>
<property name="minPoolSize">5</property>
</named-config>
</c3p0-config>
package cn.zr.testfilter.pojo;
public class User {
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public User() {
super();
}
public User(String name, Integer age) {
super();
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "User [name=" + name + ", age=" + age + "]";
}
}
package cn.zr.testfilter.Utils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.sql.DataSource;
import cn.zr.testfilter.pojo.User;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class ConnectionUtils {
public static void main(String[] args) {
ConnectionUtils utils = new ConnectionUtils();
List<User> list = utils.getData();
System.out.println(list);
}
public List<User> getData(){
List<User> list = new ArrayList<User>();
Connection connection = ConnectionUtils.getConnection();
String sql = "SELECT NAME,AGE FROM USERTEST";
PreparedStatement pStatement = null;
ResultSet rSet = null;
try {
pStatement = (PreparedStatement) connection.prepareStatement(sql);
rSet = pStatement.executeQuery();
while (rSet.next()) {
User user = new User(rSet.getString("name"), rSet.getInt("age"));
list.add(user);
}
return list;
} catch (SQLException e) {
e.printStackTrace();
}finally{
try {
if (rSet != null) {
rSet.close();
}
if (pStatement != null) {
pStatement.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
return null;
}
public static Connection getConnection() {
DataSource ds = new ComboPooledDataSource("mysqlConnection");
try {
Connection connection = ds.getConnection();
return connection;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
/*String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/mysql";
String user = "root";
String password = "";
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Connection connection = null;
try {
connection = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
e.printStackTrace();
}
return connection;*/
}
}