两种方式 获取数据库某个表中所有的数据数量条数
public int getAllEmps(){
//第一种方式 纯JDBC方式
// Connection conn=null;
// PreparedStatement ps=null;
// ResultSet rs=null;
// try {
// conn=C3Pool.getConnection();
// String sql="select count(*) from emp";
// ps = conn.prepareStatement(sql);
// rs = ps.executeQuery();
// int num=0;
// while(rs.next()){
// num=rs.getInt(1);
// }
// return num;
// } catch (SQLException e) {
// throw new RuntimeException(e);
// }finally{
// C3Pool.close(conn, ps, rs);
// }
//第二种方式 借助dbutils工具
try {
QueryRunner qr=new QueryRunner(C3Pool.getDataSource());
String sql="select count(*) from emp";
BigDecimal big =(BigDecimal)qr.query(sql, new ScalarHandler());
int num=big.intValue();
return num;
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
-------------------工具类-----------------------
package cn.gdpe.util;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class C3Pool{
private static ComboPooledDataSource dataSource=null;
//xml配置方式
static{
dataSource=new ComboPooledDataSource();
}
public static Connection getConnection(){
Connection conn=null;
try {
conn=dataSource.getConnection();
return conn;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public static DataSource getDataSource(){
return dataSource;
}
public static void close(Connection conn,Statement st){
try {
if(conn!=null){
conn.close();
}
if(st!=null){
st.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void close(Connection conn,Statement st ,ResultSet rs){
try {
if(rs!=null){
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
close(conn,st);
}
}
}
-----------------------c3po配置文件-----------------------
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<default-config>
<property name="driverClass">oracle.jdbc.driver.OracleDriver</property>
<property name="jdbcUrl">jdbc:oracle:thin:@127.0.0.1:1521:orcl</property>
<property name="user">scott</property>
<property name="password">root</property>
<property name="initialPoolSize">5</property>
<property name="maxPoolSize">5</property>
<property name="minPoolSize">1</property>
<property name="acquireIncrement">2</property>
</default-config>
</c3p0-config>