JDBC 与C3p0连接数据库回顾

package com.ddcash.jdbc.jdbc ;

import com.mchange.v2.c3p0.ComboPooledDataSource ;
import com.mchange.v2.c3p0.DataSources ;

import java.sql.* ;

/**
* Description: xxxxx
*
* @author : zhoushiwen
* Created_Date : 2017/10/11 15:25
*/
public class JDBCTest {

private static ComboPooledDataSource cpds ;
private final String selectSql = "select * from t_ddq_customer" ;
private final String insertSql = "insert into t_ddq_channel values('4','test1','test1','0',now(),now())" ;
private final String batchInsert = "insert into t_ddq_channel values(?,'test1','test1','0',now(),now())" ;

static {
cpds = new ComboPooledDataSource() ;
// 加载数据库驱动
try {
cpds .setDriverClass( "com.mysql.jdbc.Driver" ) ;
} catch (Exception e1) {
e1.printStackTrace() ;
}
// 设置访问数据库的地址、用户名和密码
cpds .setJdbcUrl( "jdbc:mysql://10.1XXXXXX:3306/ddq_reborn?useUnicode=true&characterEncoding=utf-8" ) ;
cpds .setUser( "XXXX" ) ;
cpds .setPassword( "XXXX" ) ;

// 设置 C3P0 的一些配置,不设置则使用默认值
cpds .setMinPoolSize( 5 ) ;
cpds .setAcquireIncrement( 5 ) ;
cpds .setMaxPoolSize( 20 ) ;
cpds .setMaxStatements( 180 ) ;


}

public static Connection getConnection () {
String url = "jdbc:mysql://XXXXXXXXX:3306/ddq_reborn?useUnicode=true&characterEncoding=utf-8" ;
String password = "xxxx" ;
String username = "xxxx" ;
String driver = "com.mysql.jdbc.Driver" ;
Connection con = null;
try {
Class. forName (driver) ;
con = DriverManager. getConnection (url , username , password) ;
} catch (Exception e) {
e.printStackTrace() ;
}
return con ;
}

public static Connection getConnectionByC3p0 () throws Exception {
Connection con = null;

con = cpds .getConnection() ;
return con ;
}

public static void select () {
String sql = "select * from t_ddq_customer" ;
try {
PreparedStatement prep = JDBCTest. getConnectionByC3p0 ().prepareStatement(sql) ;
ResultSet result = prep.executeQuery() ;
int col = result.getMetaData().getColumnCount() ;
while (result.next()) {
for ( int i = 1 ; i <= col ; i++) {
System. out .print(result.getString(i) + " " ) ;
}
System. out .println( "-----------------------" ) ;
}
} catch (Exception e) {
e.printStackTrace() ;
}

}

/**
* 插入
*
* @param sql
* @throws Exception
*/
private static void isnert (String sql) throws Exception {
PreparedStatement prep = getConnection ().prepareStatement(sql) ;
prep.execute() ;
}

/**
* 批量执行 SQL
*
* @param sql
* @throws Exception
*/
private static void batchInsert (String sql) throws Exception {
PreparedStatement prep = getConnection ().prepareStatement(sql) ;
for ( int i = 1 ; i < 5 ; i++) {
prep.setLong( 1 , i + 5 ) ;
prep.addBatch() ;
}
prep.executeBatch() ;
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值