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()
;
}
}