"JDBC" uses JDBC to connect to Oracle Database (Java reflection mechanism)

Source: Internet
Author: User
Tags reflection

Db.properties file

Driverclassname=oracle.jdbc.OracleDriverurl=jdbc:oracle:thin: @localhost: 1521: xeusername=  Systempassword=123456
db.properties

Jdbcutilproperties.java file

Encapsulation of data connections and freeing resources,

 PackageCom.xdl.util;Importjava.io.IOException;ImportJava.io.InputStream;Importjava.sql.Connection;ImportJava.sql.DriverManager;ImportJava.sql.ResultSet;Importjava.sql.SQLException;Importjava.sql.Statement;Importjava.util.Properties; Public classjdbcutilproperties { Public  StaticString Driverclassname;  Public  StaticString URL;  Public  StaticString username;  Public  StaticString password; Static {        Try {            //read the Db.properties file, the path is relative to the project's pathInputStream InputStream = jdbcutilproperties.class. getClassLoader (). getResourceAsStream ("Com/xdl/util/db.properties"); /*Properties is a key value structure*/Properties Pro=NewProperties (); Try{pro.load (InputStream); Driverclassname= Pro.getproperty ("Driverclassname"); URL= Pro.getproperty ("url"); Username= Pro.getproperty ("username"); Password= Pro.getproperty ("Password"); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace ();        } class.forname (Driverclassname); } Catch(ClassNotFoundException e) {//TODO auto-generated Catch blockE.printstacktrace (); }    }      /*How to get a database connection*/     Public  StaticConnection getconnection () {Connection conn=NULL; Try{conn=drivermanager.getconnection (URL, username, password); } Catch(SQLException e) {//TODO auto-generated Catch blockE.printstacktrace (); }        returnConn; }    /*ways to release resources*/     Public  Static  voidReleaseresource (Connection conn,statement st,resultset rs) {if(rs! =NULL){            Try{rs.close (); } Catch(SQLException e) {//TODO auto-generated Catch blockE.printstacktrace (); }finally{RS=NULL; }        }        if(St! =NULL){            Try{st.close (); } Catch(SQLException e) {//TODO auto-generated Catch blockE.printstacktrace (); }finally{St=NULL; }        }        if(Conn! =NULL){            Try{conn.close (); } Catch(SQLException e) {//TODO auto-generated Catch blockE.printstacktrace (); }finally{conn=NULL; }        }    }}
Jdbcutilproperties.java

Test.java file

 Packagecom.xdl.test;ImportJava.lang.reflect.Field;Importjava.sql.Connection;ImportJava.sql.ResultSet;ImportJava.sql.ResultSetMetaData;Importjava.sql.SQLException;Importjava.sql.Statement;Importjava.util.ArrayList;Importjava.util.List;ImportCom.xdl.entity.User;Importcom.xdl.util.JDBCUtilProperties; Public classTest1 { Public Static voidMain (string[] args) {//using the tool class to get the connectionConnection conn =NULL; Statement St=NULL; ResultSet RS=NULL; //Establish a connectionconn =jdbcutilproperties.getconnection (); //get the execution Environment        Try{St=conn.createstatement (); } Catch(SQLException e) {e.printstacktrace (); }                Try{RS= St.executequery ("SELECT * from MyUser"); //While (Rs.next ()) {//the object that wants to encapsulate the data as Java user user = new user ();//User.setid (Rs.getint ("ID"));//User.setname (rs.getstring ("NAME"));//User.setpassword (rs.getstring ("PASSWORD"));//System.out.println (user);//            }                        //The above approach is a hard-coded way, and is the most commonly used method. //The following approach is the use of a soft-coded method,//using the reflection mechanism in Java,//the current file is set up and reflected in the user class and query results, respectively.//and then assemble the above function. ResultSetMetaData RSMD =Rs.getmetadata (); //get the number of columns in this ResultSet object            intcolumns =Rsmd.getcolumncount (); String Userstr= "Com.xdl.entity.User"; List<User> datas =NewArraylist<user>(); //Move the cursor forward from the current position one             while(Rs.next ()) {//it uses the underlying information wrapper object to get the class object of the user class.class<?> U =Class.forName (USERSTR); Object obj=NULL; //get the User objectobj =u.newinstance (); Field[] FS=U.getdeclaredfields ();  for(inti = 1; I <= columns; i++) {                         for(Field f:fs) {//determine if the User object has fields equal to the MyUser table                        if(F.getname (). toUpperCase (). Equals (Rsmd.getcolumnname (i))) {//the type name of the current field is number                            if(Rsmd.getcolumntypename (i). Equals ("number")) {                                //to remove access checks for the user classF.setaccessible (true); Try {                                    //Insert the corresponding value into the user objectf.setint (obj, Rs.getint (Rsmd.getcolumnname (i))); } Catch(IllegalArgumentException |illegalaccessexception e) {                                    //TODO auto-generated Catch blockE.printstacktrace (); }                            }                            //the type name of the current field is Varchar2                            if(Rsmd.getcolumntypename (i). Equals ("VARCHAR2") {f.setaccessible (true); Try{f.set (obj, rs.getstring (Rsmd.getcolumnname (i))); } Catch(IllegalArgumentException |illegalaccessexception e) {                                    //TODO auto-generated Catch blockE.printstacktrace ();                }                            }                        }                    }                                    } //stores the current user object in a user collectionDatas.add ((User) obj); }             for(user user:datas) {System.out.println (user); }        } Catch(SQLException e) {e.printstacktrace (); } Catch(ClassNotFoundException E1) {//TODO auto-generated Catch blockE1.printstacktrace (); } Catch(instantiationexception E1) {//TODO auto-generated Catch blockE1.printstacktrace (); } Catch(illegalaccessexception E1) {//TODO auto-generated Catch blockE1.printstacktrace (); } finally{jdbcutilproperties.releaseresource (conn, St, RS); }    }}
Test.java

"JDBC" uses JDBC to connect to Oracle Database (Java reflection mechanism)

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.