//Utils
1 import com.mchange.v2.c3p0.ComboPooledDataSource; 2 import javax.sql.DataSource; 3 import java.sql.Connection; 4 import java.sql.ResultSet; 5 import java.sql.SQLException; 6 import java.sql.Statement; 7 8 public class JdbcUtils_C3P0 { 9 private static DataSource dataSource = null; 10 static { 11 try{ 12 dataSource = new ComboPooledDataSource("MYSQL");//配置文件写法 13 }catch (Exception e){ 14 e.printStackTrace(); 15 } 16 } 17 //获取连接 18 public static Connection getConnection() throws SQLException { 19 return dataSource.getConnection(); 20 } 21 //释放资源 22 public static void release(Connection conn, Statement st, ResultSet rs){ 23 if(rs!=null){ 24 try{ 25 rs.close(); 26 } catch (SQLException e) { 27 e.printStackTrace(); 28 } 29 } 30 if(st!=null){ 31 try { 32 st.close(); 33 } catch (SQLException e) { 34 e.printStackTrace(); 35 } 36 } 37 if(conn!=null){ 38 try { 39 conn.close(); 40 } catch (SQLException e) { 41 e.printStackTrace(); 42 } 43 } 44 45 } 46 }
//Test
1 public class TestC3P0 { 2 public static void main(String[] args) { 3 Connection conn = null; 4 PreparedStatement st = null; 5 ResultSet rs = null; 6 try { 7 conn = JdbcUtils_C3P0.getConnection(); 8 9 String sql = "select * from users where id =?"; 10 11 st = conn.prepareStatement(sql); 12 13 st.setInt(1,1); 14 15 rs = st.executeQuery(); 16 17 if(rs.next()){ 18 System.out.println(rs.getString("name")); 19 } 20 } catch (SQLException e){ 21 e.printStackTrace(); 22 }finally { 23 JdbcUtils.release(conn,st,rs); 24 } 25 } 26 27 }
//C3P0
1 <?xml version="1.0" encoding="UTF-8"?> 2 <c3p0-config> 3 <default-config> <!--默认配置 --> 4 <!--mysql数据库连接的各项参数--> 5 <property name="driverClass">com.mysql.cj.jdbc.Driver</property> 6 <property name="jdbcUrl">jdbc:mysql://localhost:3306/jdbcstudy?serverTimezone=GMT%2B8</property> 7 <property name="user">root</property> 8 <property name="password">123456789</property> 9 <!--配置数据库连接池的初始连接数、最小链接数、获取连接数、最大连接数、最大空闲时间--> 10 <property name="initialPoolSize">10</property> 11 <property name="minPoolSize">10</property> 12 <property name="acquireIncrement">5</property> 13 <property name="maxPoolSize">100</property> 14 <property name="maxIdleTime">30</property> 15 </default-config> 16 <!--自定义属性池 --> 17 <name-config name = "MYSQL"> 18 <!--mysql数据库连接的各项参数--> 19 <property name="driverClass">com.mysql.cj.jdbc.Driver</property> 20 <property name="jdbcUrl">jdbc:mysql://localhost:3306/jdbcstudy?serverTimezone=GMT%2B8</property> 21 <property name="user">root</property> 22 <property name="password">123456789</property> 23 <!--配置数据库连接池的初始连接数、最小链接数、获取连接数、最大连接数、最大空闲时间--> 24 <property name="initialPoolSize">10</property> 25 <property name="minPoolSize">10</property> 26 <property name="acquireIncrement">5</property> 27 <property name="maxPoolSize">100</property> 28 <property name="maxIdleTime">30</property> 29 </name-config> 30 </c3p0-config>
标签:10,JDBC,rs,C3P0,st,conn,sql,null,连接池 From: https://www.cnblogs.com/kidzxy/p/16792360.html