java mysql 查询数量_两种方式 获取数据库某个表中所有的数据数量条数

这篇博客介绍了两种方法来获取MySQL数据库中表的记录数量。第一种方法是使用纯JDBC,包括建立连接、执行SQL(查询所有列的数量)和遍历结果集来获取总数。第二种方法借助了dbutils工具,通过QueryRunner和ScalarHandler实现相同的功能,简化了JDBC的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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配置文件-----------------------

oracle.jdbc.driver.OracleDriver

jdbc:oracle:thin:@127.0.0.1:1521:orcl

scott

root

5

5

1

2

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值