1. 程式人生 > >jdbc及C3P0連線資料庫的方法

jdbc及C3P0連線資料庫的方法

一、jdbc連線資料庫

jdbcUtil:

public class JdbcUtil {

	private static String url = "jdbc:oracle:thin:@127.0.0.1:15211:orcl";
	private static String user = "root";
	private static String password = "root";
	private static String driver = "oracle.jdbc.OracleDriver";
	// 連線資料庫
	public static Connection getConnection() {
		Connection con = null;
		try {
			// 初始化驅動
			Class.forName(driver);
			// 獲取資料庫連線
			con = DriverManager.getConnection(url, user, password);
			System.out.println("資料庫初始化成功!");
		} catch (Exception e) {
			System.out.println("資料庫初始化失敗!");
		}

		return con;
	}

	// 關閉資料庫連線
	public static void conClose(Connection con, PreparedStatement st,
			ResultSet rs) {

		try {
			if (con != null) {
				con.close();
			}
			if (st != null) {
				con.close();
			}
			if (rs != null) {
				con.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

}

基於jdbc的crud:

	// 儲存
	public static boolean save(User user) {
		Connection con = JdbcUtil.getConnection();
		String sql = "insert into Tuser(id,username,password) values(?,?,?)";
		PreparedStatement ps = null;
		int n = 0;
		try {
			ps = con.prepareStatement(sql);
			ps.setInt(1, user.getId());
			ps.setString(2, user.getUsername());
			ps.setString(3, user.getPassword());
			n = ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JdbcUtil.conClose(con, ps, null);
		}
		if (n > 0) {
			return true;
		}

		return false;

	}

	// 查詢
	public static User query(String name) {
		Connection con = JdbcUtil.getConnection();
		String sql = "select * from Tuser where username=?";
		PreparedStatement ps = null;
		ResultSet rs = null;// 定義一個結果集
		User user = null;
		try {
			ps = con.prepareStatement(sql);
			ps.setString(1, name);
			rs = ps.executeQuery();
			while (rs.next()) {
				user = new User();
				user.setId(rs.getInt(1));
				user.setUsername(rs.getString(2));
				user.setPassword(rs.getString(3));
			}

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JdbcUtil.conClose(con, ps, rs);
		}
		return user;

	}

二、c3p0連線資料庫

配置檔案dataSource.properties:

c3p0.driverClass=oracle.jdbc.OracleDriver
c3p0.jdbcUrl=jdbc:oracle:thin:@127.0.0.0:15211:orcl
c3p0.user=root
c3p0.password=root
c3p0.minPoolSize=0
c3p0.maxPoolSize=10
#連線的最大空閒時間,如果超過這個時間,連線還沒被使用,則會斷開
c3p0.maxIdleTime=60
#連線池無空閒連線時一次性建立新連線的個數
c3p0.acquireIncrement=2
#連線池為資料來源快取的PreparedStatement總數。為0不快取
c3p0.maxStatements=0
#連線池獲得新連線失敗時重試額次數
c3p0.acquireRetryAttempts=30
DataBaseName=Oracle

當然也可以配置在xml裡,這裡就配在properties檔案裡了。

工具類:

import java.beans.PropertyVetoException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.springframework.jdbc.core.JdbcTemplate;
import com.mchange.v2.c3p0.ComboPooledDataSource;

public class c3p0Util {

	protected static ComboPooledDataSource ds = new ComboPooledDataSource(true);
	protected static JdbcTemplate jdbcTemplate;

	static {
		try {
			initDBInFo();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * @throws IOException
	 * @throws PropertyVetoException
	 * @Title: initDBInFo
	 * @Description: 初始化資料庫連線池
	 */
	private static void initDBInFo() throws IOException, PropertyVetoException {
		Properties pro = new Properties();
		InputStream in = Thread.currentThread().getContextClassLoader()
				.getResourceAsStream("dataSource.properties");
		pro.load(in);
		try {
			 ds.setDriverClass(pro.getProperty("c3p0.driverClass"));
			 ds.setJdbcUrl(pro.getProperty("c3p0.jdbcUrl"));
			 ds.setUser(pro.getProperty("c3p0.user"));
			 ds.setPassword(pro.getProperty("c3p0.password"));
			 ds.setMinPoolSize(Integer.valueOf(pro.getProperty("c3p0.minPoolSize")));
			 ds.setMaxPoolSize(Integer.valueOf(pro.getProperty("c3p0.maxPoolSize")));
			 ds.setMaxIdleTime(Integer.valueOf(pro.getProperty("c3p0.maxIdleTime")));
			 ds.setAcquireIncrement(Integer.valueOf(pro.getProperty("c3p0.acquireIncrement")));
			 ds.setMaxStatements(Integer.valueOf(pro.getProperty("c3p0.maxStatements")));
			 ds.setIdleConnectionTestPeriod(Integer.valueOf(pro.getProperty("c3p0.idleConnectionTestPeriod")));
			 ds.setAcquireRetryAttempts(Integer.valueOf(pro.getProperty("c3p0.acquireRetryAttempts")));
			jdbcTemplate = new JdbcTemplate(ds);

		} catch (NumberFormatException e) {
			System.out.println("資料庫連線池初始化失敗:" + e);
			e.printStackTrace();
		}
	}

	
}

這裡用到了spring的JdbcTemplate,需要自己下載jar包哦。

測試類:

String sql = "select * from Tuser";
		try {
			List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
			System.out.println(list);
		} catch (Exception e) {
			e.printStackTrace();
		}
大功告成!