JDBC實現用於操作資料庫Mysql的工具類JDBCTools

來源:互聯網
上載者:User

標籤:

  下面用一個統一的工具類封裝一套用於資料庫的JDBC操作:包括 1)擷取資料庫連結資源  2)釋放資料庫連結資源,包括Connection,Statement,PreparedStatement,ResultSet等 3)資料庫的更新操作,包括插入,刪除,修改  4)資料庫的查詢操作

  首先是1)擷取資料庫連結資源

     /** * 擷取資料庫連結的靜態方法  這樣子就保證了只載入一次檔案的操作 * @return * @throws Exception */public static Connection getConn() throws Exception{String jdbcDriver=null;String url=null;String user=null;String password=null;Properties p=new Properties();InputStream is=JDBCTools.class.getClassLoader().getResourceAsStream("jdbc.properties");p.load(is);jdbcDriver=p.getProperty("jdbcDriver");url=p.getProperty("url");user=p.getProperty("user");password=p.getProperty("password");Class.forName(jdbcDriver);return DriverManager.getConnection(url, user, password);}

  

    其中  jdbc.properties  是屬性設定檔,因為是通過  類名.class.getClassLoader().getResourceAsStream("jdbc.properties");擷取的,所以

該屬性設定檔需要放置在src目錄下。其內容的例子:

  jdbcDriver=com.mysql.jdbc.Driver
  url=jdbc:mysql://localhost:3306/test
  user=root
  password=root

    接著是2)釋放資料庫連結資源

 

        /** * 關閉從資料庫伺服器等索取的資源:先關閉後擷取的 * @param conn * @param pstmt */public static void closeResource(Connection conn,Statement stmt,ResultSet rs){if (rs != null) {try {rs.close();} catch (SQLException e) {e.printStackTrace();}}if (stmt != null) {try {stmt.close();} catch (SQLException e) {e.printStackTrace();}}if (conn != null) {try {conn.close();} catch (SQLException e) {e.printStackTrace();}}    

 

   由於PreparedStatement是Statement的子介面,所以該方法也適合傳入PreparedStatement的對象

 

  然後是3)資料庫的更新操作,包括插入,刪除,修改 

 

        /** * 統一的更新操作 Statement:insert update delete * @param conn * @param sql * @throws Exception */public void update(String sql){Connection conn=null;Statement stmt=null;try {conn=JDBCTools.getConn();stmt=conn.createStatement();stmt.executeUpdate(sql);} catch (Exception e) {e.printStackTrace();} finally{closeResource(conn, stmt, null);}}/** * 適用於PreparedStatment * @param sql * @param args */public void update2(String sql,Object ... args){Connection conn=null;PreparedStatement pstmt=null;ResultSet rs=null;try {conn=JDBCTools.getConn();pstmt=conn.prepareStatement(sql);for(int i=0;i<args.length;i++){pstmt.setObject(i+1, args[i]);}pstmt.executeUpdate();} catch (Exception e) {e.printStackTrace();} finally{JDBCTools.closeResource(conn, pstmt, rs);}}        

 

   其中這段代碼:for(int i=0;i<args.length;i++){ pstmt.setObject(i+1, args[i]); } 的意思在於:設定SQL語句中的預留位置 ? 的值。

 

  最後是4)資料庫的查詢操作:在這裡寫了通用的方法,目的在於將查詢得到的結果集封裝在統一的實體中,這裡採用了泛型,反射機制的知識

 

        /** * 泛型方法  反射機制  通用的查詢方法儲存實體 * @param clazz * @param sql * @param args * @return */public <T> T getT(Class<T> clazz,String sql,Object ... args){T t=null;Connection conn=null;PreparedStatement pstmt=null;ResultSet rs=null;ResultSetMetaData rsmd=null;try {conn=JDBCTools.getConn();pstmt=conn.prepareStatement(sql);for(int i=0;i<args.length;i++){pstmt.setObject(i+1, args[i]);}rs=pstmt.executeQuery();if (rs.next()) {t=clazz.newInstance();Map<String, Object> map=new HashMap<String, Object>();//解析sql擷取對象rsmd = rs.getMetaData();int numberOfColumns = rsmd.getColumnCount();for(int i=0;i<numberOfColumns;i++){
                        //擷取列的名字,如果有別名,則擷取的是別名String columnName=rsmd.getColumnLabel(i+1); map.put(columnName, rs.getObject(columnName));}if (map.size() > 0) {for(Map.Entry<String, Object> entry: map.entrySet()){String columnName=entry.getKey();Object columnValue=entry.getValue();Field field = t.getClass().getDeclaredField(columnName);field.setAccessible(true);field.set(t, columnValue);}}}} catch (Exception e) {e.printStackTrace();} finally{JDBCTools.closeResource(conn, pstmt, rs);}return t;}

 

JDBC實現用於操作資料庫Mysql的工具類JDBCTools

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.