java連接數據庫方式(一):傳統JDBC + 連接池

作者的個人分享網:分享時刻【www.itison.cn】

用了太久的框架,傳統的JDBC也不能忘記,以下是傳統的JDBC實現連接數據庫

使用傳統的JDBC實現數據庫連接,一般要DIY一個工具類,這個工具類中,最好使用連接池,數據庫連接池有很多,JNDI,DBCP,C3P0等皆可以實現,這裏我使用的是C3P0連接池。
C3P0連接池的配置文件c3p0-config.xml如下:

<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>

  <default-config>
    <property name="driverClass">com.mysql.jdbc.Driver</property>
	<property name="jdbcUrl">jdbc:mysql:///fruit</property>
	<property name="user">root</property>
	<property name="password">123456</property>
	<property name="initialPoolSize">50</property>
	<property name="maxPoolSize">100</property>
  </default-config>
  
  <named-config name="namedConfig"> 
    <property name="driverClass">com.mysql.jdbc.Driver</property>
	<property name="jdbcUrl">jdbc:mysql:///fruit</property>
	<property name="user">root</property>
	<property name="password">123456</property>
  </named-config>
  
</c3p0-config>

沒有使用C3P0連接池之前,獲取數據庫連接對象是這樣的(這是最原始的):

// 獲取數據庫連接對象
public static Connection getConnection() {

	if (conn != null) {
		return conn;
	}

	try {

		// 加載驅動類,不同的數據庫軟件驅動類不同
		Class.forName(MYSQL_DRIVER);
		// 使用DriverManager獲得連接對象,其中URL每個數據庫不同
		conn = DriverManager.getConnection(MYSQL_URL, MYSQL_USER,
				MYSQL_PASS);
		
		System.out.println("數據庫已連接...");

	} catch (ClassNotFoundException | SQLException e) {
		e.printStackTrace();
	}

	// 返回獲得的連接對象
	return conn;
}

DIY封裝的工具類加上C3P0連接池之後,獲取數據庫連接對象由C3P0連接池完成。
加上C3P0連接池後,DIY的工具類如下:

package com.fruitsys.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

/**
 *  These are data base utils
 * @author LIU
 * @version 1.0 2017-09-21
 */
public class BaseDao {

	/**
	 * Create Connection
	 */
	private static Connection conn = null;
	
	/**
	 * Create ResultSet
	 */
	private static ResultSet rs = null;
	
	/**
	 * Create PreparedStatement
	 */
	private static PreparedStatement pstmt = null;

	/**
	 * Create ComboPooledDataSource
	 */
	private static ComboPooledDataSource dataSource = new ComboPooledDataSource();
	
	/**
	 * Get dataSource
	 */
	public DataSource getDataSource(){
		return dataSource;
	}
	
	/**
	 * Get a Connection 
	 *TODO
	 *LIU
	 * @return Connection
	 * pm4:42:19
	 */
	public Connection getConnection(){
		try {
			return dataSource.getConnection();
		} catch (Exception e) {
			throw new RuntimeException(e);		
		}
	}
	
	
	/**
	 * Update information by sql
	 *TODO
	 *LIU
	 * @param sql
	 * @param objects
	 * @return int
	 * pm4:42:37
	 */
	public int updateBySql(String sql, Object ...objects){
		
		int result = 0;
		conn = getConnection();
		
		try {
			pstmt = conn.prepareStatement(sql);
			if (objects.length > 0) {
				for (int i = 0; i < objects.length; i++) {
					pstmt.setObject(i+1, objects[i]);
				}
			}
			
			result = pstmt.executeUpdate();
			
		} catch (Exception e) {
			e.printStackTrace();
		}

		return result;
	}
	
	
	
	/**
	 * Get information from database by sql
	 * TODO
	 * LIU
	 * @param sql
	 * @param objects
	 * @return ResultSet
	 * pm4:43:22
	 */
	public ResultSet selectBySql(String sql, Object ...objects){
		
		conn = getConnection();
		
		try {
			pstmt = conn.prepareStatement(sql);
			if (objects.length > 0) {
				for (int i = 0; i < objects.length; i++) {
					pstmt.setObject(i+1, objects[i]);
				}
			}
			
			rs = pstmt.executeQuery();
			
		} catch (Exception e) {
			e.printStackTrace();
		}

		return rs;
	}

	

	
	/**
	 * Close Connetion,ResultSet or PreparedStatement
	 *TODO
	 *LIU
	 *pm 11:16:00
	 */
	public void close() {
		try {
			if(rs != null){
				rs.close();
			}
			if(pstmt != null){
				pstmt.close();
			}
			if (conn != null) {
				conn.close();
				conn = null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}



在數據訪問實現類中使用DIY的工具類,實現對數據的增刪改查。
數據訪問實現類如下:

package com.fruitsys.dao.impl;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import com.fruitsys.bean.Fruit;
import com.fruitsys.bean.Page;
import com.fruitsys.dao.BaseDao;
import com.fruitsys.dao.FruitDao;

/**
 * 水果信息數據訪問實現類
 * @author LIU
 * @version 1.0 2017-10-17
 */
public class FruitDaoImpl extends BaseDao implements FruitDao {

	/**
	 * 獲取總記錄數
	 *TODO
	 *LIU
	 * @return
	 *下午4:06:37
	 */
	@Override
	public int getAllCount() {
		// TODO Auto-generated method stub
		String sql = "select count(id) from fruit";
		try {
			ResultSet rs = selectBySql(sql);
			if(rs.next()){
				return rs.getInt(1);
			}
		} catch (Exception e) {
			// TODO: handle exception
		}finally{
			close();
		}
		return 0;
	}

	
	/**
	 * 獲取當前頁的信息
	 *TODO
	 *LIU
	 * @param page
	 * @return
	 *下午4:09:03
	 */
	@Override
	public List<Fruit> showCurrList(Page page) {
		// TODO Auto-generated method stub
		String sql = "select id,type,breed,area,brief,weight,price from fruit limit ?,?";
		List<Fruit> fruitList = new ArrayList<Fruit>();
		
		try {
			ResultSet rs = selectBySql(sql, page.getStart(), page.getCurrCount());
			while(rs.next()){
				Fruit f = new Fruit();
				f.setId(rs.getInt("id"));
				f.setType(rs.getString("type"));
				f.setBreed(rs.getString("breed"));
				f.setArea(rs.getString("area"));
				f.setBrief(rs.getString("brief"));
				f.setWeight(rs.getInt("weight"));
				f.setPrice(rs.getDouble("price"));
			
				fruitList.add(f);
			}
		} catch (Exception e) {
			// TODO: handle exception
		}finally{
			close();
		}
		
		return fruitList;
	}

	
	/**
	 * 顯示一條信息詳情
	 *TODO
	 *LIU
	 * @return
	 *下午4:10:18
	 */
	@Override
	public Fruit showOne(int id) {
		// TODO Auto-generated method stub
		String sql = "select id,type,breed,area,brief,weight,price from fruit where id=?";
		
		try {
			ResultSet rs = selectBySql(sql, id);
			while(rs.next()){
				Fruit f = new Fruit();
				f.setId(rs.getInt("id"));
				f.setType(rs.getString("type"));
				f.setBreed(rs.getString("breed"));
				f.setArea(rs.getString("area"));
				f.setBrief(rs.getString("brief"));
				f.setWeight(rs.getInt("weight"));
				f.setPrice(rs.getDouble("price"));
			
				return f;
			}
		} catch (Exception e) {
			// TODO: handle exception
		}finally{
			close();
		}
		
		return null;
	}

	
	/**
	 * 刪除一條信息
	 *TODO
	 *LIU
	 * @param id
	 * @return
	 *下午4:09:48
	 */
	@Override
	public int deleteFruit(int id) {
		// TODO Auto-generated method stub
		String sql = "delete from fruit where id=?";
		int result = updateBySql(sql, id);
		return result;
	}

}

項目目錄結構如下:

這裏寫圖片描述

發佈了43 篇原創文章 · 獲贊 86 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章