DBUtil工具類

package com.shxt.common.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 劉文銘
 * @日期 : 2012-6-13
 * @描述 : 連接數據庫工具類
 * @版本 : v0.1
 */
public class DBUtil {
	private Connection conn;
	private PreparedStatement statement;
	private Statement stmt;
	private ResultSet rs = null;
	/** 連接數據庫URL thin連接方式 : 協議+主機地址+資源名稱 */
	private String url = "jdbc:oracle:thin:@localhost:1521:shxtdb";
	/** 用戶名 */
	private String userName = "shxt";
	/** 密碼 */
	private String password = "shxt";

	/**
	 * 靜態代碼塊
	 */
	static {
		try {
			// 加載驅動
			Class.forName("oracle.jdbc.driver.OracleDriver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 獲得Connection
	 */
	public Connection getConn() {
		try {
			conn = DriverManager.getConnection(url, userName, password);
			return conn;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 獲取執行sql的Statement對象
	 * */
	public Statement getStmt() {
		try {
			conn = getConn();
			stmt = conn.createStatement();
			return stmt;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 使用Statement操作--查詢
	 * 
	 * @param sql
	 * @return ResultSet
	 * */
	public ResultSet query(String sql) {
		try {
			rs = getStmt().executeQuery(sql);
			return rs;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			colse();
		}
	}

	/**
	 * 執行數據更新的方法
	 * 
	 * @param sql
	 *            String 的SQL語句
	 * @return Integer 類型的數據 表示受影響的行數
	 */
	public int update(String sql) {
		try {
			return getStmt().executeUpdate(sql);
		} catch (Exception e) {
			e.printStackTrace();
			return -1;
		} finally {
			colse();
		}
	}

	/**
	 * 查詢數據 返回的是一個ArrayList對象,對象中的每一個元素是一個HashMap對象
	 * 
	 * @param sql
	 *            String 查詢語句
	 * @return ArrayList 結果集
	 * @throws Exception
	 */

	public List<Map<String, String>> queryByList(String sql) {
		try {
			List<Map<String, String>> list = new ArrayList<Map<String, String>>();
			rs = getStmt().executeQuery(sql);
			// 得到結果集(rs)的結構信息,比如字段數、字段名等
			ResultSetMetaData rsmd = rs.getMetaData();
			// 得到數據集的列數
			int columncount = rsmd.getColumnCount();
			while (rs.next()) {
				Map<String, String> map = new HashMap<String, String>();
				for (int i = 0; i < columncount; i++) {
					String key = rsmd.getColumnName(i + 1);
					String value = rs.getString(key);
					map.put(key, value);
				}
				list.add(map);
			}
			return list;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			colse();
		}
	}

	/**
	 * 批量更新
	 * 
	 * @param sqls
	 *            String 查詢語句數組
	 * @return int[] 計數組成的數組
	 * @throws Exception
	 */
	public int[] updateBatch(String[] sqls) {
		stmt = getStmt();
		try {
			startTransaction();
			for (String sql : sqls) {
				stmt.addBatch(sql);// 將所有的SQL語句添加到Statement中
			}
			int[] batchResultList = stmt.executeBatch();
			endTransaction();
			return batchResultList; // 返回更新計數組成的數組。
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			colse();
		}
		return null;
	}

	/**
	 * 預處理語句查詢結果並封裝到List. 
	 * @param
	 * 	sql語句. 
	 * @param 可變參數. 
	 * @return
	 * 返回List. 
	 * @throws SQLException when the query execution failed.
	 */
	public List<Map<String, String>> queryForList(String query,String... params) throws SQLException {
		ResultSet resultSet = null;
		List<Map<String, String>> result;
		try {
			statement = conn.prepareStatement(query);
			for (int i = 0; i < params.length; i++) {
				statement.setString(i + 1, params[i]);
			}
			resultSet = statement.executeQuery();
			result = new ArrayList<Map<String, String>>();
			while (resultSet.next()) {
				Map<String, String> rowMap = new HashMap<String, String>();
				for (int i = 1; i <= resultSet.getMetaData().getColumnCount(); i++) {
					rowMap.put(resultSet.getMetaData().getColumnLabel(i),
					        resultSet.getString(i));
				}
				result.add(rowMap);
			}
		} finally {
			colse();
		}
		return result;
	}

	/**
	 * 結束事務
	 * */
	public void endTransaction() throws Exception {
		if (conn == null) {
			conn = getConn();
		}
		try {
			conn.commit();
			conn.close();
		} catch (Exception e) {
			conn.rollback();

		}
	}

	/**
	 * 開啓事務
	 * */
	public void startTransaction() throws SQLException {
		if (conn == null) {
			conn = getConn();
		}
		try {
			conn.setAutoCommit(false);// 設置連接不自動提交,即用該連接進行的操作都不更新到數據庫
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 數據庫關閉操作
	 * 
	 * 要按照順序關 rs-->stmt-->conn
	 * */
	public void colse() {
		if (rs != null) {
			try {
				rs.close();
			} catch (Exception e) {
				System.out.println("關閉結果集對象時出錯!");
				e.printStackTrace();
			}
		}
		if (stmt != null) {
			try {
				stmt.close();
			} catch (Exception e) {
				System.out.println("關閉語句對象時出錯!");
				e.printStackTrace();
			}
		}
		if (conn != null) {
			try {
				conn.close();
			} catch (Exception e) {
				System.out.println("關閉連接對象時出錯!");
				e.printStackTrace();
			}
		}
	}
	
	
	/*
	 * 知識擴展:getColumnLabel(int)返回該int所對應的列的顯示標題 getColumnName(int)返回該int所對應的列的在數據庫中的名稱
	 */

}

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