06.数据库连接工具类

package com.serlfy.study.utils;

import java.beans.PropertyVetoException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import com.mchange.v2.c3p0.ComboPooledDataSource;

public class DBUtils {
private static String driver;
private static String url;
private static String username;
private static String password;
private static int init;
private static int maxactive;
private static ComboPooledDataSource bds;

static {
	Properties cfg = new Properties();
	InputStream inStream = DBUtils.class.getClassLoader().getResourceAsStream("db.properties");
	try {
		cfg.load(inStream);
		driver = cfg.getProperty("jdbc.driver");
		url = cfg.getProperty("jdbc.url");
		username = cfg.getProperty("jdbc.username");
		password = cfg.getProperty("jdbc.password");
		bds = new ComboPooledDataSource();
		init = Integer.parseInt(cfg.getProperty("init"));
		maxactive = Integer.parseInt(cfg.getProperty("maxactive"));
		try {
			bds.setDriverClass(driver);
			bds.setJdbcUrl(url);
			bds.setUser(username);
			bds.setPassword(password);
			bds.setInitialPoolSize(init);
			bds.setMaxPoolSize(maxactive);
		} catch (PropertyVetoException e) {
			e.printStackTrace();
		}
	} catch (IOException e) {
		e.printStackTrace();
	}

}

public static Connection getConnection() {
	try {
		Connection conn = bds.getConnection();
		return conn;
	} catch (SQLException e) {
		e.printStackTrace();
	}
	return null;
}

public static void closeConnection(Connection conn) {
	if (conn != null) {
		try {
			// 把事务恢复成自动提交再归还
			conn.setAutoCommit(true);
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}

public static void rollback(Connection conn) {
	if (conn != null) {
		try {
			conn.rollback();
		} catch (SQLException e1) {
			e1.printStackTrace();
		}
	}
}

public static void main(String[] args) {
	Connection conn = getConnection();
	System.out.println(conn);
}

}

posted @ 2022-08-27 11:49  NIANER2011  阅读(71)  评论(0编辑  收藏  举报