封裝JDBC—非框架開發必備的封裝類

阿木俠發表於2017-06-07
一些小型的專案,有時不想使用框架如MyBatis,Hibernate等開發時,往往在資料持久化時操作比較繁瑣,以下提供了對JDBC的封裝類,簡化JDBC操作。
為了更客觀展示MyJDBC,我們通過一般的JDBC連線資料庫的增刪改查來對比。
JDBC連線資料庫操作通常的做法都是先建立一個公共類,來配置資料庫資訊,載入驅動等,這裡不展示公共類(網上到處都是)。
以下對比增刪改查:

增(通常的程式碼):

private static int insert(Student student) {
        Connection conn = getConn();
        int i = 0;
        String sql = "insert into students (Name,Sex,Age) values(?,?,?)";
        PreparedStatement pstmt;
        try {
            pstmt = (PreparedStatement) conn.prepareStatement(sql);
            pstmt.setString(1, student.getName());
            pstmt.setString(2, student.getSex());
            pstmt.setString(3, student.getAge());
            i = pstmt.executeUpdate();
            pstmt.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return i;
    }
使用MyJDBC:
public void insert() throws Exception{
       String SQL = "insert into user_info(username,password) value (?,?)";
       MyJDBC.insert(SQL, true, "阿木俠","12345");
   }
對於單條資料的新增:
不需要使用類似pstmt.setString(1, student.getName());這樣的語句一條一條對應占位符,MyJDBC提供了封裝:MyJDBC.insert(SQL, autoGeneratedKeys, params)
SQL:需要執行的 INSERT 語句
autoGeneratedKeys:指示是否需要返回由資料庫產生的鍵,當autoGeneratedKeys為true時,返回由資料庫產生的主鍵的值,false時返回記錄改變的條數。
params:使用了可變引數,無論多少位佔位符,依次寫入即可。

刪:

private static int delete(String name) {
    Connection conn = getConn();
    int i = 0;
    String sql = "delete from students where Name='" + name + "'";
    PreparedStatement pstmt;
    try {
        pstmt = (PreparedStatement) conn.prepareStatement(sql);
        i = pstmt.executeUpdate();
        System.out.println("resutl: " + i);
        pstmt.close();
        conn.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return i;
}
使用MyJDBC:
public void delete() throws Exception{
	String username = "阿木";
        String SQL = "delete from user_info where username like '%"+username+"%'";
        MyJDBC.execute(SQL);
    }

改:

private static int update(Student student) {
    Connection conn = getConn();
    int i = 0;
    String sql = "update students set Age='" + student.getAge() + "' where Name='" + student.getName() + "'";
    PreparedStatement pstmt;
    try {
        pstmt = (PreparedStatement) conn.prepareStatement(sql);
        i = pstmt.executeUpdate();
        System.out.println("resutl: " + i);
        pstmt.close();
        conn.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return i;
}
使用MyJDBC:
public void update() throws Exception{
        String SQL = "update user_info set password=? where id=2";
        MyJDBC.execute(SQL, "123321");
    }

查:

private static Integer getAll() {
    Connection conn = getConn();
    String SQL = "select id,password from user_info where username= ?";
    PreparedStatement pstmt;
    try {
        pstmt = (PreparedStatement)conn.prepareStatement(SQL);
        ResultSet rs = pstmt.executeQuery();
        while (rs.next()) {
            User user = new User();
	        user.setId(rs.getInt(1));
	        user.setUsername(rs.getString(2));
	        user.setPassword(rs.getString(3));
	        System.out.println("使用者資訊"+user);
            System.out.println("");
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return null;
}
使用MyJDBC:
public void query() throws Exception{
	String name = "阿木俠";
	String SQL = "select id,password from user_info where username= ?";
	ResultSet rs = MyJDBC.query(SQL,name);
	    if(rs.next()){
	        User user = new User();
	        user.setId(rs.getInt(1));
	        user.setUsername(name);
	        user.setPassword(rs.getString(2));
	        System.out.println("使用者資訊"+user);
	  }
    }

我們可以看到,程式碼確實簡化了好多,Statement,Connection,ResultSet都不需要去手動操作,關閉,全部由MyJDBC代理。
不僅如此,還提供了execute()方法對SQL進行基本的操作。
下面貼出MyJDBC封裝類:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @author
 */
public final class MyJDBC {

    private static String connect;
    private static String driverClassName;
    private static String URL;
    private static String username;
    private static String password;
    private static boolean autoCommit;

    /** 宣告一個 Connection型別的靜態屬性,用來快取一個已經存在的連線物件 */
    private static Connection conn;

    static {
	config();
    }

    /**
     * 開頭配置自己的資料庫資訊
     */
    private static void config() {
	/*
	 * 獲取驅動
	 */
	driverClassName = "com.mysql.jdbc.Driver";
	/*
	 * 獲取URL
	 */
	URL = "jdbc:mysql://localhost:3306/spring?useUnicode=true&characterEncoding=utf8";
	/*
	 * 獲取使用者名稱
	 */
	username = "root";
	/*
	 * 獲取密碼
	 */
	password = "1234";
	/*
	 * 設定是否自動提交,一般為false不用改
	 */
	autoCommit = false;

    }

    /**
     * 載入資料庫驅動類
     */
    private static boolean load() {
	try {
	    Class.forName(driverClassName);
	    return true;
	} catch (ClassNotFoundException e) {
	    System.out.println("驅動類 " + driverClassName + " 載入失敗");
	}

	return false;
    }

    /**
     * 專門檢查快取的連線是否不可以被使用 ,不可以被使用的話,就返回 true
     */
    private static boolean invalid() {
	if (conn != null) {
	    try {
		if (conn.isClosed() || !conn.isValid(3)) {
		    return true;
		    /*
		     * isValid方法是判斷Connection是否有效,如果連線尚未關閉並且仍然有效,則返回 true
		     */
		}
	    } catch (SQLException e) {
		e.printStackTrace();
	    }
	    /*
	     * conn 既不是 null 且也沒有關閉 ,且 isValid 返回 true,說明是可以使用的 ( 返回 false )
	     */
	    return false;
	} else {
	    return true;
	}
    }

    /**
     * 建立資料庫連線
     */
    public static Connection connect() {
	if (invalid()) { /* invalid為true時,說明連線是失敗的 */
	    /* 載入驅動 */
	    load();
	    try {
		/* 建立連線 */
		conn = DriverManager.getConnection(URL, username, password);
	    } catch (SQLException e) {
		System.out.println("建立 " + connect + " 資料庫連線失敗 , " + e.getMessage());
	    }
	}
	return conn;
    }

    /**
     * 設定是否自動提交事務
     **/
    public static void transaction() {

	try {
	    conn.setAutoCommit(autoCommit);
	} catch (SQLException e) {
	    System.out.println("設定事務的提交方式為 : " + (autoCommit ? "自動提交" : "手動提交") + " 時失敗: " + e.getMessage());
	}

    }

    /**
     * 建立 Statement 物件
     */
    public static Statement statement() {
	Statement st = null;
	connect();
	/* 如果連線是無效的就重新連線 */
	transaction();
	/* 設定事務的提交方式 */
	try {
	    st = conn.createStatement();
	} catch (SQLException e) {
	    System.out.println("建立 Statement 物件失敗: " + e.getMessage());
	}

	return st;
    }

    /**
     * 根據給定的帶引數佔位符的SQL語句,建立 PreparedStatement 物件
     * 
     * @param SQL
     *            帶引數佔位符的SQL語句
     * @return 返回相應的 PreparedStatement 物件
     */
    private static PreparedStatement prepare(String SQL, boolean autoGeneratedKeys) {

	PreparedStatement ps = null;
	connect();
	/* 如果連線是無效的就重新連線 */
	transaction();
	/* 設定事務的提交方式 */
	try {
	    if (autoGeneratedKeys) {
		ps = conn.prepareStatement(SQL, Statement.RETURN_GENERATED_KEYS);
	    } else {
		ps = conn.prepareStatement(SQL);
	    }
	} catch (SQLException e) {
	    System.out.println("建立 PreparedStatement 物件失敗: " + e.getMessage());
	}

	return ps;

    }


    public static ResultSet query(String SQL, Object... params) {

	if (SQL == null || SQL.trim().isEmpty() || !SQL.trim().toLowerCase().startsWith("select")) {
	    throw new RuntimeException("你的SQL語句為空或不是查詢語句");
	}
	ResultSet rs = null;
	if (params.length > 0) {
	    /* 說明 有引數 傳入,就需要處理引數 */
	    PreparedStatement ps = prepare(SQL, false);
	    try {
		for (int i = 0; i < params.length; i++) {
		    ps.setObject(i + 1, params[i]);
		}
		rs = ps.executeQuery();
	    } catch (SQLException e) {
		System.out.println("執行SQL失敗: " + e.getMessage());
	    }
	} else {
	    /* 說明沒有傳入任何引數 */
	    Statement st = statement();
	    try {
		rs = st.executeQuery(SQL); // 直接執行不帶引數的 SQL 語句
	    } catch (SQLException e) {
		System.out.println("執行SQL失敗: " + e.getMessage());
	    }
	}

	return rs;

    }


    private static Object typeof(Object o) {
	Object r = o;

	if (o instanceof java.sql.Timestamp) {
	    return r;
	}
	// 將 java.util.Date 轉成 java.sql.Date
	if (o instanceof java.util.Date) {
	    java.util.Date d = (java.util.Date) o;
	    r = new java.sql.Date(d.getTime());
	    return r;
	}
	// 將 Character 或 char 變成 String
	if (o instanceof Character || o.getClass() == char.class) {
	    r = String.valueOf(o);
	    return r;
	}
	return r;
    }


    public static boolean execute(String SQL, Object... params) {
	if (SQL == null || SQL.trim().isEmpty() || SQL.trim().toLowerCase().startsWith("select")) {
	    throw new RuntimeException("你的SQL語句為空或有錯");
	}
	boolean r = false;
	/* 表示 執行 DDL 或 DML 操作是否成功的一個標識變數 */

	/* 獲得 被執行的 SQL 語句的 字首 */
	SQL = SQL.trim();
	SQL = SQL.toLowerCase();
	String prefix = SQL.substring(0, SQL.indexOf(" "));
	String operation = ""; // 用來儲存操作型別的 變數
	// 根據字首 確定操作
	switch (prefix) {
	case "create":
	    operation = "create table";
	    break;
	case "alter":
	    operation = "update table";
	    break;
	case "drop":
	    operation = "drop table";
	    break;
	case "truncate":
	    operation = "truncate table";
	    break;
	case "insert":
	    operation = "insert :";
	    break;
	case "update":
	    operation = "update :";
	    break;
	case "delete":
	    operation = "delete :";
	    break;
	}
	if (params.length > 0) { // 說明有引數
	    PreparedStatement ps = prepare(SQL, false);
	    Connection c = null;
	    try {
		c = ps.getConnection();
	    } catch (SQLException e) {
		e.printStackTrace();
	    }
	    try {
		for (int i = 0; i < params.length; i++) {
		    Object p = params[i];
		    p = typeof(p);
		    ps.setObject(i + 1, p);
		}
		ps.executeUpdate();
		commit(c);
		r = true;
	    } catch (SQLException e) {
		System.out.println(operation + " 失敗: " + e.getMessage());
		rollback(c);
	    }

	} else { // 說明沒有引數

	    Statement st = statement();
	    Connection c = null;
	    try {
		c = st.getConnection();
	    } catch (SQLException e) {
		e.printStackTrace();
	    }
	    // 執行 DDL 或 DML 語句,並返回執行結果
	    try {
		st.executeUpdate(SQL);
		commit(c); // 提交事務
		r = true;
	    } catch (SQLException e) {
		System.out.println(operation + " 失敗: " + e.getMessage());
		rollback(c); // 回滾事務
	    }
	}
	return r;
    }

    /*
     * 
     * @param SQL
     *            需要執行的 INSERT 語句
     * @param autoGeneratedKeys
     *            指示是否需要返回由資料庫產生的鍵
     * @param params
     *            將要執行的SQL語句中包含的引數佔位符的 引數值
     * @return 如果指定 autoGeneratedKeys 為 true 則返回由資料庫產生的鍵; 如果指定 autoGeneratedKeys
     *         為 false 則返回受當前SQL影響的記錄數目
     */
    public static int insert(String SQL, boolean autoGeneratedKeys, Object... params) {
	int var = -1;
	if (SQL == null || SQL.trim().isEmpty()) {
	    throw new RuntimeException("你沒有指定SQL語句,請檢查是否指定了需要執行的SQL語句");
	}
	// 如果不是 insert 開頭開頭的語句
	if (!SQL.trim().toLowerCase().startsWith("insert")) {
	    System.out.println(SQL.toLowerCase());
	    throw new RuntimeException("你指定的SQL語句不是插入語句,請檢查你的SQL語句");
	}
	// 獲得 被執行的 SQL 語句的 字首 ( 第一個單詞 )
	SQL = SQL.trim();
	SQL = SQL.toLowerCase();
	if (params.length > 0) { // 說明有引數
	    PreparedStatement ps = prepare(SQL, autoGeneratedKeys);
	    Connection c = null;
	    try {
		c = ps.getConnection(); // 從 PreparedStatement 物件中獲得 它對應的連線物件
	    } catch (SQLException e) {
		e.printStackTrace();
	    }
	    try {
		for (int i = 0; i < params.length; i++) {
		    Object p = params[i];
		    p = typeof(p);
		    ps.setObject(i + 1, p);
		}
		int count = ps.executeUpdate();
		if (autoGeneratedKeys) { // 如果希望獲得資料庫產生的鍵
		    ResultSet rs = ps.getGeneratedKeys(); // 獲得資料庫產生的鍵集
		    if (rs.next()) { // 因為是儲存的是單條記錄,因此至多返回一個鍵
			var = rs.getInt(1); // 獲得值並賦值給 var 變數
		    }
		} else {
		    var = count; // 如果不需要獲得,則將受SQL影像的記錄數賦值給 var 變數
		}
		commit(c);
	    } catch (SQLException e) {
		System.out.println("資料儲存失敗: " + e.getMessage());
		rollback(c);
	    }
	} else { // 說明沒有引數
	    Statement st = statement();
	    Connection c = null;
	    try {
		c = st.getConnection(); // 從 Statement 物件中獲得 它對應的連線物件
	    } catch (SQLException e) {
		e.printStackTrace();
	    }
	    // 執行 DDL 或 DML 語句,並返回執行結果
	    try {
		int count = st.executeUpdate(SQL);
		if (autoGeneratedKeys) { // 如果企望獲得資料庫產生的鍵
		    ResultSet rs = st.getGeneratedKeys(); // 獲得資料庫產生的鍵集
		    if (rs.next()) { // 因為是儲存的是單條記錄,因此至多返回一個鍵
			var = rs.getInt(1); // 獲得值並賦值給 var 變數
		    }
		} else {
		    var = count; // 如果不需要獲得,則將受SQL影像的記錄數賦值給 var 變數
		}
		commit(c); // 提交事務
	    } catch (SQLException e) {
		System.out.println("資料儲存失敗: " + e.getMessage());
		rollback(c); // 回滾事務
	    }
	}
	return var;
    }

    /** 提交事務 */
    private static void commit(Connection c) {
	if (c != null && !autoCommit) {
	    try {
		c.commit();
	    } catch (SQLException e) {
		e.printStackTrace();
	    }
	}
    }

    /** 回滾事務 */
    private static void rollback(Connection c) {
	if (c != null && !autoCommit) {
	    try {
		c.rollback();
	    } catch (SQLException e) {
		e.printStackTrace();
	    }
	}
    }


    /**
     *  釋放資源
     *   **/
    public static void release(Object cloaseable) {

	if (cloaseable != null) {

	    if (cloaseable instanceof ResultSet) {
		ResultSet rs = (ResultSet) cloaseable;
		try {
		    rs.close();
		} catch (SQLException e) {
		    e.printStackTrace();
		}
	    }

	    if (cloaseable instanceof Statement) {
		Statement st = (Statement) cloaseable;
		try {
		    st.close();
		} catch (SQLException e) {
		    e.printStackTrace();
		}
	    }

	    if (cloaseable instanceof Connection) {
		Connection c = (Connection) cloaseable;
		try {
		    c.close();
		} catch (SQLException e) {
		    e.printStackTrace();
		}
	    }

	}

    }

}

以上,沒有最方便的程式碼,只會有更方便的,歡迎大家指正,有什麼好的建議歡迎留言,隨時作出調整。

相關文章