c3p0工具类,使用了xml配置文件

c3p0工具类,使用了xml配置文件

package com.dbsy.utils;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/*
c3p0工具类,使用了xml配置文件
 */
public class C3P0UtilsXML {
    private static ComboPooledDataSource dataSource =new ComboPooledDataSource();

    public static Connection getConnection(){
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException("获取数据库连接对象失败:"+e);
        }
    }
    public static void close(ResultSet rs, Statement stat,Connection conn){
        if (rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (stat!=null){
            try {
                stat.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
package com.dbsy.test;

import com.dbsy.utils.C3P0Utils;
import com.dbsy.utils.C3P0UtilsXML;

import java.sql.*;

/*
测试c3p0连接池工具类
 */
public class Demo01TestC3P0Utils {
    public static void main(String[] args) throws SQLException {
//        test1();
        test2();
    }

    private static void test2() throws SQLException {
        Connection conn = C3P0UtilsXML.getConnection();
        PreparedStatement pst = conn.prepareStatement("select * from users where uid in(?,?,?)");
        pst.setObject(1,1);
        pst.setObject(2,2);
        pst.setObject(3,3);

        ResultSet rs = pst.executeQuery();

        while (rs.next()){
            int uid = rs.getInt("uid");
            String username = rs.getString("username");
            String password = rs.getString("password");
            System.out.println(uid+"\t"+username+"\t"+password);
        }
        C3P0UtilsXML.close(rs,pst,conn);
    }

    private static void test1() throws SQLException {
        Connection conn = C3P0Utils.getConnection();
//        System.out.println(conn);

        Statement stat = conn.createStatement();
        ResultSet rs = stat.executeQuery("select * from users");

        while (rs.next()){
            int uid = rs.getInt("uid");
            String username = rs.getString("username");
            String password = rs.getString("password");
            System.out.println(uid+"\t"+username+"\t"+password);
        }
        C3P0Utils.close(rs,stat,conn);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值