1. 程式人生 > >Java 自定義JDBC類庫

Java 自定義JDBC類庫

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

public class MySQLHelper implements AutoCloseable {
	// tool variables
	private static String sql;
	private static StringBuilder sbuilder;
	static {
		sbuilder = new StringBuilder();
	}
	private String info;

	private String url;
	private String host;
	private int port;
	private String dbName;

	private String usr;
	private String pwd;

	private Connection conn;
	private Statement stmt;

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getHost() {
		return host;
	}

	public void setHost(String host) {
		this.host = host;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public String getDbName() {
		return dbName;
	}

	public void setDbName(String dbName) {
		this.dbName = dbName;
	}

	public String getUsr() {
		return usr;
	}

	public void setUsr(String usr) {
		this.usr = usr;
	}

	public String getPwd() {
		return pwd;
	}

	public void setPwd(String pwd) {
		this.pwd = pwd;
	}

	public String getInfo() {
		return info;
	}

	public MySQLHelper() throws ClassNotFoundException, SQLException {
		this.host = "localhost";
		this.port = 3306;
		this.dbName = "test";
		this.usr = "root";
		this.pwd = "123456";
		this.url = "jdbc:mysql://localhost:3306";
		ConnectDB();
	}

	public MySQLHelper(String url, String usr, String pwd)
			throws ClassNotFoundException, SQLException {
		this.url = url;
		this.usr = usr;
		this.pwd = pwd;
		ConnectDB();
	}

	public MySQLHelper(String host, int port, String usr, String pwd)
			throws ClassNotFoundException, SQLException {
		this.host = host;
		this.port = port;
		this.usr = usr;
		this.pwd = pwd;
		this.url = "jdbc:mysql://" + this.host + ":" + this.port;
		ConnectDB();
	}

	public MySQLHelper(String host, int port, String dbName, String usr,
			String pwd) throws ClassNotFoundException, SQLException {
		this.host = host;
		this.port = port;
		this.dbName = dbName;
		this.usr = usr;
		this.pwd = pwd;
		this.url = "jdbc:mysql://" + this.host + ":" + this.port + "/"
				+ this.dbName;
		ConnectDB();
	}

	/**
	 * 註冊JDBC驅動 + 建立資料庫連線
	 * 
	 * @return
	 * @throws ClassNotFoundException
	 * @throws SQLException
	 */
	private Connection ConnectDB() throws ClassNotFoundException, SQLException {
		try {
			// 註冊JDBC類
			Class.forName("com.mysql.jdbc.Driver");
			// 開啟資料庫連線
			this.conn = DriverManager.getConnection(this.url+"?useUnicode=true&characterEncoding=UTF8", this.usr,
					this.pwd);
			this.stmt = conn.createStatement();
			this.info = "資料庫連線成功!";
		} catch (ClassNotFoundException e) {
			this.info = "com.mysql.jdbc.Driver匯入失敗!";
			throw new ClassNotFoundException(this.info);
		} catch (SQLException e) {
			this.info = "MySQL資料庫連線失敗!";
			throw new SQLException(this.info);
		}
		return this.conn;
	}

	/**
	 * 建立資料庫
	 * 
	 * @param newDBName
	 * @throws SQLException
	 */
	public void CreateDB(String newDBName) throws SQLException {
		sql = "CREATE DATABASE IF NOT EXISTS " + newDBName
				+ " DEFAULT CHARSET = utf8";
		try {
			stmt.executeUpdate(sql);
			this.info = "資料庫建立成功";
		} catch (SQLException e) {
			this.info = "建立資料庫失敗";
			throw e;
		}
	}

	/**
	 * 建立資料表
	 * 
	 * @param newTBName
	 *            新的資料表名
	 * @param dbName
	 *            資料庫名
	 * @param properties
	 *            欄位屬性
	 * @throws SQLException
	 */
	public void CreateTable(String dbName, String newTBName,
			Map<String, String> properties) throws SQLException {
		setDbName(dbName);
		if (properties.size() == 0)
			throw new SQLException("欄位以及欄位資訊[properties]不能為空!");
		sbuilder.delete(0, sbuilder.length());
		sbuilder.append(String.format("CREATE TABLE IF NOT EXISTS `%s`.`%s` (",
				dbName, newTBName));

		for (Map.Entry<String, String> entry : properties.entrySet()) {
			sbuilder.append(entry.getKey() + " " + entry.getValue() + ",");
		}
		sbuilder.deleteCharAt(sbuilder.length() - 1);
		sbuilder.append(")");
		sql = sbuilder.toString();
		try {
			this.info = "建立資料表" + newTBName + "成功!";
			stmt.executeUpdate(sql);
		} catch (SQLException e) {
			this.info = "建立資料表" + newTBName + "失敗!";
			System.out.println(sql);
			throw e;
		}
	}

	/**
	 * 建立資料表
	 * 
	 * @param newTBName
	 *            新的資料表名
	 * @param properties
	 *            欄位屬性
	 * @throws SQLException
	 */
	public void CreateTable(String newTBName, Map<String, String> properties)
			throws SQLException {
		if (this.dbName == null || this.dbName == "")
			throw new SQLException("請先選擇一個數據庫!");
		else
			CreateTable(this.dbName, newTBName, properties);
	}

	/**
	 * 刪除資料庫
	 * 
	 * @param dbName
	 *            資料庫名
	 * @throws SQLException
	 */
	public void DropDB(String dbName) throws SQLException {
		sql = "DROP DATABASE IF EXISTS " + dbName;
		try {
			stmt.executeUpdate(sql);
			this.info = "資料庫刪除成功";
		} catch (SQLException e) {
			this.info = "資料庫刪除失敗!" + sql;
			throw e;
		}
	}

	/**
	 * 刪除資料庫
	 * 
	 * @throws SQLException
	 */
	public void DropDB() throws SQLException {
		if (this.dbName == null || this.dbName == "")
			throw new SQLException("請先選擇一個數據庫!");
		else
			DropDB(this.dbName);
	}

	/**
	 * 刪除資料表
	 * 
	 * @param dbName
	 *            資料庫名
	 * @param tbName
	 *            資料表名
	 * @throws SQLException
	 */
	public void DropTable(String dbName, String tbName) throws SQLException {
		sql = String.format("DROP TABLE IF EXISTS `%s`.`%s`", dbName, tbName);
		try {
			stmt.executeUpdate(sql);
			this.info = "資料表刪除成功";
		} catch (SQLException e) {
			this.info = "資料表刪除失敗" + sql;
			throw e;
		}
	}

	/**
	 * 刪除資料表
	 * 
	 * @param tbName
	 *            資料表名
	 * @throws SQLException
	 */
	public void DropTable(String tbName) throws SQLException {
		if (this.dbName == null || this.dbName == "")
			throw new SQLException("請先選擇一個數據庫!");
		else
			DropTable(this.dbName, tbName);
	}

	/**
	 * 查詢資料表中全部資訊
	 * 
	 * @param tbName
	 * @return
	 * @throws SQLException
	 */
	public ResultSet selectAll(String tbName) throws SQLException {
		sql = String.format("SELECT * FROM `%s`.`%s`", this.dbName, tbName);
		try {
			this.info = "資料庫SELECT-ALL查詢成功";
			return stmt.executeQuery(sql);
		} catch (SQLException e) {
			this.info = "資料庫SELECT-ALL查詢失敗";
			throw e;
		}
	}

	/**
	 * 查詢資料表中的部分資訊
	 * 
	 * @param field
	 * @param tbName
	 * @param condition
	 * @return
	 * @throws SQLException
	 */
	public ResultSet select(String field, String tbName, String condition)
			throws SQLException {
		if ("" == condition)
			condition = "1";
		sql = String.format("SELECT %s FROM `%s`.`%s` where %s", field,
				this.dbName, tbName, condition);
		try {
			this.info = "資料庫SELECT查詢成功";
			return stmt.executeQuery(sql);
		} catch (SQLException e) {
			this.info = "資料庫SELECT查詢失敗";
			throw e;
		}
	}

	/**
	 * 插入資料到資料表
	 * 
	 * @param dbName
	 *            資料庫名稱
	 * @param tbName
	 *            資料表名稱
	 * @param item
	 *            記錄對映表
	 * @throws SQLException
	 */
	public void insert(String dbName, String tbName, Map<String, Object> item)
			throws SQLException {
		sbuilder.delete(0, sbuilder.length());
		sbuilder.append(String.format("INSERT INTO `%s`.`%s` ( ", dbName,
				tbName));
		for (Map.Entry<String, Object> e : item.entrySet()) {
			sbuilder.append(e.getKey() + ",");
		}
		sbuilder.setCharAt(sbuilder.length() - 1, ')');
		sbuilder.append(" VALUES ( ");
		for (Map.Entry<String, Object> e : item.entrySet()) {
			sbuilder.append("'" + e.getValue() + "'" + ",");
		}
		sbuilder.setCharAt(sbuilder.length() - 1, ')');
		sql = sbuilder.toString();
		try {
			int ret = stmt.executeUpdate(sql);
			this.info = "資料庫INSERT更新成功, " + ret + "行受影響";
		} catch (SQLException e) {
			System.out.println(sql);
			this.info = "資料庫INSERT更新失敗";
			throw e;
		}
	}

	/**
	 * 插入資料到資料表,請確保MySQLHelper物件dbName已經設定
	 * 
	 * @param tbName
	 *            資料表名稱
	 * @param item
	 *            記錄對映表
	 * @throws SQLException
	 */
	public void insert(String tbName, Map<String, Object> item)
			throws SQLException {
		if (this.dbName == null || this.dbName == "")
			throw new SQLException("請先選擇一個數據庫!");
		else
			insert(this.dbName, tbName, item);
	}

	/**
	 * 更新資料表
	 * 
	 * @param fieldName
	 *            欄位名
	 * @param fieldValue
	 *            欄位值
	 * @param condition
	 *            更新條件
	 * @param tbName
	 *            資料表名
	 * @throws SQLException
	 */
	public void update(String fieldName, String fieldValue, String condition,
			String tbName) throws SQLException {
		if ("" == condition)
			condition = "1";
		sql = String.format("UPDATE `%s`.`%s` SET %s='%s' WHERE %s",
				this.dbName, tbName, fieldName, fieldValue, condition);
		try {
			int ret = stmt.executeUpdate(sql);
			this.info = "資料庫UPDATE更新成功, " + ret + "行受影響";
		} catch (SQLException e) {
			System.out.println(sql);
			this.info = "資料庫UPDATE更新失敗";
			throw e;
		}
	}

	/**
	 * 刪除資料表中指定的元素,請確保MySQLHelper物件dbName已經設定
	 * 
	 * @param tbName
	 * @param condition
	 * @return
	 * @throws SQLException
	 */
	public void delete(String tbName, String condition) throws SQLException {
		if (this.dbName == null || this.dbName == "")
			throw new SQLException("請先選擇一個數據庫!");
		else
			delete(this.dbName, tbName, condition);
	}

	public void delete(String dbName, String tbName, String condition)
			throws SQLException {
		sql = String.format("DELETE FROM `%s`.`%s` WHERE %s", dbName, tbName,
				condition);
		try {
			int ret = stmt.executeUpdate(sql);
			this.info = "資料表DELETE操作刪除成功, " + ret + "行受影響!";
		} catch (SQLException e) {
			this.info = "資料表DELETE操作刪除失敗";
			throw e;
		}
	}

	/**
	 * 釋放資料庫連線資源
	 * 
	 * @throws SQLException
	 */
	public void release() throws SQLException {
		try {
			if (null != stmt)
				stmt.close();
			if (null != conn)
				conn.close();
			this.info = "釋放連線成功";
		} catch (SQLException e) {
			this.info = "釋放連線失敗";
			throw e;
		}

	}

	/**
	 * 打印出所有的資料庫名稱
	 * 
	 * @throws SQLException
	 */
	public void showDBs() throws SQLException {
		ResultSet rs = stmt.executeQuery("show databases");
		printResult(rs);
	}

	/**
	 * 列印資料庫的查詢結果集ResultSet
	 * 
	 * @param result
	 * @throws SQLException
	 */
	public static void printResult(ResultSet result) throws SQLException {
		// 獲取欄位名
		ResultSetMetaData rsmd = result.getMetaData();
		int L = rsmd.getColumnCount();
		ArrayList<String> fieldNames = new ArrayList<>();
		for (int i = 1; i <= L; i++) {
			fieldNames.add(rsmd.getColumnName(i));
			System.out.print(rsmd.getColumnName(i) + (i == L ? "\n" : "\t"));
		}
		while (result.next()) {
			for (int i = 1; i <= L; i++) {
				System.out.print(result.getString(i) + (i == L ? "\n" : "\t"));
			}
		}
	}

	/**
	 * try 自動關閉, 自動釋放連線資源
	 */
	@Override
	public void close() throws Exception {
		// TODO Auto-generated method stub
		this.release();
		System.out.println(this.info);
	}
}