link
1、添加jar包
2、编写配置文件c3p0-config.xml,
放在classpath中,或classes目录中(XX项目/src/c3p0-config.xml)
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<default-config>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/day14</property>
<property name="user">root</property>
<property name="password">00000000</property>
<property name="initialPoolSize">10</property>
<property name="maxIdleTime">30</property>
<property name="maxPoolSize">100</property>
<property name="minPoolSize">10</property>
</default-config>
</c3p0-config>
3、编写工具类:
public class C3P0Util {
private static DataSource dataSource = new ComboPooledDataSource();
public static DataSource getDataSource() {
return dataSource;
}
//获取连接
public static Connection getConnection(){
try {
return dataSource.getConnection();
} catch (SQLException e) {
throw new RuntimeException("服务器繁忙");
}
}
public static void release(Connection conn,Statement stmt,ResultSet rs){
//关闭连接
if(rs!=null){
try {
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
rs = null;
}
if(stmt!=null){
try {
stmt.close();
} catch (Exception e) {
e.printStackTrace();
}
stmt = null;
}
if(conn!=null){
try {
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
conn = null;
}
}
}
4、编写sql语句操作数据库:
public class BookDaoImpl implements BookDao{
public List<Book> findAllBooks() throws SQLException{
QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());
return qr.query("select * from book", new BeanListHandler<Book>(Book.class));
}
public void addBook(Book book) throws SQLException{
QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());
qr.update("insert into book values(?, ?, ?, ?, ?, ?)",
book.getId(),book.getName(), book.getPrice(),
book.getPnum(), book.getCategory(), book.getDescription());
}
}