jdbc连接池c3p0连接
程序员文章站
2022-04-20 08:28:20
...
public class DataSource {
private static DataSource datasource;
private ComboPooledDataSource cpds;
private DataSource() throws IOException, SQLException, PropertyVetoException { //该类构造时即创建c3p0数据库连接池
cpds = new ComboPooledDataSource();
cpds.setDriverClass("com.mysql.jdbc.Driver"); //loads the jdbc driver
cpds.setJdbcUrl("jdbc:mysql://localhost:3306/stopsix_two_phase");
cpds.setUser("root");
cpds.setPassword("root");
cpds.setMinPoolSize(5); //最小连接数目
cpds.setAcquireIncrement(5); //连接不够时增加数目
cpds.setMaxPoolSize(20); //最大连接数目
}
public static DataSource getInstance() throws IOException, SQLException, PropertyVetoException { //获得单例
if (datasource == null) {
datasource = new DataSource();
return datasource;
} else {
return datasource;
}
}
public Connection getConnection() throws SQLException {
return this.cpds.getConnection();
}
}
调用:
public class Get {
public static void main(String[] args) throws IOException, PropertyVetoException {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
connection = DataSource.getInstance().getConnection();
statement = connection.createStatement();
resultSet = statement.executeQuery("select 1+1 as numb");
while (resultSet.next()) {
System.out.println("numb: " + resultSet.getInt("numb"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (resultSet != null) try { resultSet.close(); } catch (SQLException e) {e.printStackTrace();}
if (statement != null) try { statement.close(); } catch (SQLException e) {e.printStackTrace();}
if (connection != null) try { connection.close(); } catch (SQLException e) {e.printStackTrace();}
}
}
}
jar包:c3p0-0.9.5.2.jar,mchange-commons-java-0.2.11.jar,mysql-connector-java-5.1.33.jar
上一篇: Android,DataBinding的官方双向绑定
下一篇: 软键盘的收起与关闭