JDBC implements the tool class for manipulating database MySQL Jdbctools

Source: Internet
Author: User

The following uses a unified tool class to encapsulate a set of JDBC operations for the database: including 1) Get database link resources 2) Release database link resources, including connection,statement,preparedstatement,resultset, etc. 3) database update operations, including INSERT, delete, modify 4) database query operations

First 1) Get the database Link resource

/** * static method to get database links  This ensures that only one file is loaded once * @return * @throws Exception */public static Connection Getconn () throws Excepti On{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");p assword=p.getproperty ("password"); Class.forName (jdbcdriver); return drivermanager.getconnection (URL, user, password);}

Where jdbc.properties is the property profile, because it is through the class name . Class.getclassloader (). getResourceAsStream ("jdbc.properties"); GET, so

The property profile needs to be placed in the SRC directory. Examples of its contents:

Jdbcdriver=com.mysql.jdbc.driver
Url=jdbc:mysql://localhost:3306/test
User=root
Password=root

Then 2) Release the database Link resource

        /** * Shut down resources requested from the database server: first closed after getting the * @param conn * @param pstmt */public static void Closeresource (Connection conn,statement St Mt,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 ()}}    

because PreparedStatement is a sub-interface of statement, this method is also suitable for incoming PreparedStatement objects

and then 3) database update operations, including INSERT, delete, modify

        /** * Unified Update Operation Statement:insert Update DELETE * @param conn * @param SQL * @throws Exception */public void Update (String sq L) {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);}} /** * for preparedstatment * @param SQL * @param args */public void Update2 (String sql,object ... args) {Connection Conn=nul L PreparedStatement Pstmt=null; ResultSet rs=null;try {conn=jdbctools.getconn ();p stmt=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);}}        

where this code: for (int i=0;i<args.length;i++) {pstmt.setobject (i+1, args[i]): Sets the value of the placeholder in the SQL statement.

Finally 4) database query operations: Here The general method is written in order to encapsulate the result set of the query into a unified entity, where the knowledge of generics and reflection mechanism is used.

/** * Generic method A common query method for the reflection mechanism stores entities * @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 ();p stmt=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> ();//Parse SQL Get Object RSMD = Rs.getmetadata (); int NumberOfColumns = Rsmd.getcolumncount (); for (int i=0;i<numberofcolumns;i++) {
                         //Gets the name of the column and, if there is an alias, gets the aliasString 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 (); O Bject 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 implements the tool class for manipulating database MySQL Jdbctools

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.