JDBC深度封裝的工具類(具有高度的可重用性)

package com.util;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
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.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

public class JdbcUtils
{

	// 表示定義數據庫的用戶名
	private final String USERNAME = "root";
	// 定義數據庫的密碼
	private final String PASSWORD = "admin";
	// 定義數據庫的驅動信息
	private final String DRIVER = "com.mysql.jdbc.Driver";
	// 定義訪問數據庫的地址
	private final String URL = "jdbc:mysql://localhost:3306/mydb";
	// 定義數據庫的鏈接
	private Connection connection;
	// 定義sql語句的執行對象
	private PreparedStatement pstmt;
	// 定義查詢返回的結果集合
	private ResultSet resultSet;

	public JdbcUtils()
	{
		try
		{
			Class.forName(DRIVER);
			System.out.println("註冊驅動成功!!");
		}
		catch (Exception e)
		{
			// TODO: handle exception
		}
	}

	// 定義獲得數據庫的鏈接
	public Connection getConnection()
	{
		try
		{
			connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
			System.out.println("數據庫連接成功");
		}
		catch (Exception e)
		{
			// TODO: handle exception
		}
		return connection;
	}

	/**
	 * 完成對數據庫的表的添加刪除和修改的操作
	 * 
	 * @param sql
	 * @param params
	 * @return
	 * @throws SQLException
	 */
	public boolean updateByPreparedStatement(String sql, List<Object> params)
			throws SQLException
	{
		boolean flag = false;
		int result = -1;// 表示當用戶執行添加刪除和修改的時候所影響數據庫的行數
		pstmt = connection.prepareStatement(sql);
		int index = 1;
		// 填充sql語句中的佔位符
		if (params != null && !params.isEmpty())
		{
			for (int i = 0; i < params.size(); i++)
			{
				pstmt.setObject(index++, params.get(i));
			}
		}
		result = pstmt.executeUpdate();
		flag = result > 0 ? true : false;
		return flag;
	}

	/**
	 * 查詢返回單條記錄,並保存在map中
	 * 
	 * @param sql
	 * @param params
	 * @return
	 * @throws SQLException
	 */
	public Map<String, Object> findSimpleResult(String sql, List<Object> params)
			throws SQLException
	{
		Map<String, Object> map = new HashMap<String, Object>();
		int index = 1;
		pstmt = connection.prepareStatement(sql);
		if (params != null && !params.isEmpty())
		{
			for (int i = 0; i < params.size(); i++)
			{
				pstmt.setObject(index++, params.get(i));
			}
		}
		resultSet = pstmt.executeQuery();// 返回查詢結果
		// 獲取此 ResultSet 對象的列的編號、類型和屬性。
		ResultSetMetaData metaData = resultSet.getMetaData();
		int col_len = metaData.getColumnCount();// 獲取列的長度
		while (resultSet.next())// 獲得列的名稱
		{
			for (int i = 0; i < col_len; i++)
			{
				String cols_name = metaData.getColumnName(i + 1);
				Object cols_value = resultSet.getObject(cols_name);
				if (cols_value == null)// 列的值沒有時,設置列值爲“”
				{
					cols_value = "";
				}
				map.put(cols_name, cols_value);
			}
		}
		return map;
	}

	/**
	 * 查詢返回多行記錄,並保存在List<Map<String, Object>>中
	 * 
	 * @param sql
	 * @param params
	 * @return
	 * @throws SQLException
	 */
	public List<Map<String, Object>> findMoreResult(String sql,
			List<Object> params) throws SQLException
	{
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		int index = 1;
		pstmt = connection.prepareStatement(sql);
		if (params != null && !params.isEmpty())
		{
			for (int i = 0; i < params.size(); i++)
			{
				pstmt.setObject(index++, params.get(i));
			}
		}
		resultSet = pstmt.executeQuery();
		ResultSetMetaData metaData = resultSet.getMetaData();
		int cols_len = metaData.getColumnCount();
		while (resultSet.next())
		{
			Map<String, Object> map = new HashMap<String, Object>();
			for (int i = 0; i < cols_len; i++)
			{
				String cols_name = metaData.getColumnName(i + 1);
				Object cols_value = resultSet.getObject(cols_name);
				if (cols_value == null)
				{
					cols_value = "";
				}
				map.put(cols_name, cols_value);
			}
			list.add(map);
		}
		return list;
	}

	/**
	 * jdbc的封裝可以用反射機制來封裝:取得單條記錄並保存在javaBean中(這裏使用到了泛型)
	 * 
	 * @param sql
	 * @param params
	 * @param cls
	 * @return
	 * @throws Exception
	 */
	public <T> T findSimpleRefResult(String sql, List<Object> params,
			Class<T> cls) throws Exception
	{
		T resultObject = null;
		int index = 1;
		pstmt = connection.prepareStatement(sql);
		if (params != null && !params.isEmpty())
		{
			for (int i = 0; i < params.size(); i++)
			{
				pstmt.setObject(index++, params.get(i));
			}
		}
		resultSet = pstmt.executeQuery();
		ResultSetMetaData metaData = resultSet.getMetaData();
		int cols_len = metaData.getColumnCount();
		while (resultSet.next())
		{
			// 通過反射機制創建實例
			resultObject = cls.newInstance();
			for (int i = 0; i < cols_len; i++)
			{
				String cols_name = metaData.getColumnName(i + 1);
				Object cols_value = resultSet.getObject(cols_name);
				if (cols_value == null)
				{
					cols_value = "";
				}
				// 返回一個 Field 對象,該對象反映此 Class 對象所表示的類或接口的指定已聲明字段。
				Field field = cls.getDeclaredField(cols_name);
				field.setAccessible(true);// 打開javabean的訪問private權限
				field.set(resultObject, cols_value);// 爲resultObject對象的field的屬性賦值
			}
		}
		return resultObject;
	}

	/**
	 * 通過反射機制訪問數據庫 jdbc的封裝可以用反射機制來封裝:取得多條記錄並保存在javaBean的集合中中(這裏使用到了泛型)
	 * 
	 * @param <T>
	 * @param sql
	 * @param params
	 * @param cls
	 * @return
	 * @throws Exception
	 */
	public <T> List<T> findMoreRefResult(String sql, List<Object> params,
			Class<T> cls) throws Exception
	{
		List<T> list = new ArrayList<T>();
		int index = 1;
		pstmt = connection.prepareStatement(sql);
		if (params != null && !params.isEmpty())
		{
			for (int i = 0; i < params.size(); i++)
			{
				pstmt.setObject(index++, params.get(i));
			}
		}
		resultSet = pstmt.executeQuery();
		ResultSetMetaData metaData = resultSet.getMetaData();
		int cols_len = metaData.getColumnCount();
		while (resultSet.next())
		{
			T resultObject = cls.newInstance();
			for (int i = 0; i < cols_len; i++)
			{
				String cols_name = metaData.getColumnName(i + 1);
				Object cols_value = resultSet.getObject(cols_name);
				if (cols_value == null)
				{
					cols_value = "";
				}
				Field field = cls.getDeclaredField(cols_name);
				field.setAccessible(true);
				field.set(resultObject, cols_value);
			}
			list.add(resultObject);
		}
		return list;
	}

	/**
	 * 釋放所用的連接
	 */
	public void releaseConn()
	{
		if (resultSet != null)
		{
			try
			{
				resultSet.close();
			}
			catch (SQLException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if (pstmt != null)
		{
			try
			{
				pstmt.close();
			}
			catch (SQLException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if (connection != null)
		{
			try
			{
				connection.close();
			}
			catch (SQLException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	/**
	 * 將連接參數寫入配置文件
	 * 
	 * @param url
	 *            jdbc連接域名
	 * @param user
	 *            用戶名
	 * @param password
	 *            密碼
	 */
	public static void writeProperties(String url, String user, String password)
	{
		Properties pro = new Properties();
		FileOutputStream fileOut = null;
		try
		{
			fileOut = new FileOutputStream("Config.ini");
			pro.put("url", url);
			pro.put("user", user);
			pro.put("password", password);
			pro.store(fileOut, "My Config");
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		finally
		{

			try
			{
				if (fileOut != null)
					fileOut.close();
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}
		}
	}

	/**
	 * 讀取配置文件的連接參數
	 * 
	 * @return 返回list
	 */
	public static List readProperties()
	{
		List list = new ArrayList();
		Properties pro = new Properties();
		FileInputStream fileIn = null;
		try
		{
			fileIn = new FileInputStream("Config.ini");
			pro.load(fileIn);
			list.add(pro.getProperty("url"));
			list.add(pro.getProperty("user"));
			list.add(pro.getProperty("password"));
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		finally
		{

			try
			{
				if (fileIn != null)
					fileIn.close();
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}
		}
		return list;
	}

	/**
	 * 測試jdbc工具類
	 * 
	 * @param args
	 */
	public static void main(String[] args)
	{
		// TODO Auto-generated method stub
		JdbcUtils jdbcUtils = new JdbcUtils();
		jdbcUtils.getConnection();
		// String sql = "insert into userinfo(username,pswd) values(?,?)";
		// List<Object> params = new ArrayList<Object>();
		// params.add("rose");
		// params.add("123");
		// try {
		// boolean flag = jdbcUtils.updateByPreparedStatement(sql, params);
		// System.out.println(flag);
		// } catch (SQLException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
		String sql = "select * from userinfo ";
		// List<Object> params = new ArrayList<Object>();
		// params.add(1);
		/*
		 * try { List<UserInfo> list = jdbcUtils.findMoreRefResult(sql, null,
		 * UserInfo.class); System.out.println(list); } catch (Exception e) { //
		 * TODO: handle exception } finally { jdbcUtils.releaseConn(); }
		 */
	}

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章