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

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐