Detailed explanation of the encapsulation of JDBC database links and related methods, detailed explanation of jdbc database Encapsulation

Source: Internet
Author: User

Detailed explanation of the encapsulation of JDBC database links and related methods, detailed explanation of jdbc database Encapsulation

Details about the encapsulation of JDBC database links and related methods

The MySQL database is used. First, import the driver class and obtain the data link based on the database URL and user name and password. Because the MySQL database is used, its URL is usually jdbc: mysql: // host address: Port Number/database name.

The following are specific encapsulated classes that use generics and reflection, but there are still some problems, that is, some restrictions on the use of generic objects, it can only be used for objects with the same attribute name as the column name in the database table for generic objects. The initialization object must be set + attribute name. I originally wanted to determine the initialization method of this attribute through the return value type and parameter list. However, it may be that I have learned too little at present and only learned three weeks, so it is not implemented, I feel that this method is still very low and will be improved in the future. We can see the beanUtils package on the Internet. We can use map to store a column of the query and directly convert it into this object, but we just want to try the new reflection. AndThe final Garbage Collector cannot be the same as the C ++ destructor, so the database link should be closed.

Implementation Code:

Public class Consql {private static Consql consql = null; // Singleton design mode private Connection conn = null; // database link private final String url; // Database url private final String username; // database username private final String password; // Database Password // load the driver Class static {// load the Driver Class in the form of a static code block. The static code block is executed only once when the Class is loaded. try {Class. forName ("com. mysql. jdbc. driver ");} catch (ClassNotFoundException e) {e. printStackTrace () ;}// constructor private Consql (String Url, String username, String password) throws SQLException {this. url = url; this. username = username; this. password = password; open (); // create Connection} private Connection open () throws SQLException {try {// drive to obtain the database link conn = DriverManager. getConnection (url, username, password);} catch (SQLException e) {// TODO Auto-generated catch block // e. printStackTrace (); throw e;} return conn;}/*** query with restrictions * @ param SQL with placeholders? * @ Param t returns the class (T. class) * @ param params replaces the placeholder data, which is a dynamic array * @ return ArrayList <T> * @ throws SQLException */public <T> ArrayList <T> select (String SQL, class <T> t, Object... params) throws SQLException {// obtain all public methods of the T class. Method [] declaredMethods = t. getDeclaredMethods (); // create an ArrayList containing the set of objects of this type <T> arrayList = new ArrayList <> (); try (PreparedStatement pStatement = conn. prepareStatement (SQL);) {f Or (int I = 0; I <params. length; I ++) {pStatement. setObject (I + 1, params [I]);} try (ResultSet rset1_pstatement.exe cuteQuery ();) {ResultSetMetaData rData = rSet. getMetaData (); // obtain the number of columns in the query result table. int columnCount = rData. getColumnCount (); while (rSet. next () {T a = t. newInstance (); // create a generic class instance for (int I = 0; I <columnCount; I ++) {// obtain the set Method in the array, this causes limitations. Only the names of database table columns must be the same as the object names, and only the set Method String aString = "set" + rData can be used. getColumnName (I + 1 ); For (Method method: declaredMethods) {if (method. getParameterCount () = 1 & method. getReturnType (). toString (). equals ("void") & method. getName (). equalsIgnoreCase (aString) {// There is a problem here. The first two judgment conditions are basically useless, mainly because they didn't want to use the above concatenation method to determine whether to call the method of this parameter. setAccessible (true); // call the method using reflection. invoke (a, rSet. getObject (I + 1); break ;}} arrayList. add (a) ;}} catch (InstantiationException e) {// TODO Auto-generated catch Block e. printStackTrace ();} catch (IllegalAccessException e) {// TODO Auto-generated catch block e. printStackTrace ();} catch (IllegalArgumentException e) {// TODO Auto-generated catch block e. printStackTrace ();} catch (InvocationTargetException e) {// TODO Auto-generated catch block e. printStackTrace () ;}} catch (SQLException e) {// TODO Auto-generated catch block throw e;} return arrayL Ist;}/*** insert data * @ param SQL with placeholders? SQL statement * @ param params replaces the placeholder data, dynamic array * @ throws SQLException */public void insert (String SQL, Object... params) throws SQLException {try (PreparedStatement pStatement = conn. prepareStatement (SQL);) {for (int I = 0; I <params. length; I ++) {pStatement. setObject (I + 1, params [I]);} pStatement.exe cuteUpdate ();} catch (SQLException e) {// TODO Auto-generated catch block throw e ;}} /*** data update ** @ param SQL with placeholder? SQL statement * @ param params replaces the placeholder data, dynamic array * @ throws SQLException */public void update (String SQL, Object... params) throws SQLException {try (PreparedStatement pStatement = conn. prepareStatement (SQL);) {for (int I = 0; I <params. length; I ++) {pStatement. setObject (I + 1, params [I]);} pStatement.exe cuteUpdate ();} catch (SQLException e) {// TODO Auto-generated catch block throw e ;}} /*** Delete with restrictions ** @ param SQL With placeholders? SQL statement * @ param params replaces the placeholder data, dynamic array * @ throws SQLException */public void delete (String SQL, Object... params) throws SQLException {try (PreparedStatement pStatement = conn. prepareStatement (SQL);) {for (int I = 0; I <params. length; I ++) {pStatement. setObject (I + 1, params [I]);} pStatement.exe cuteUpdate ();} catch (SQLException e) {// TODO Auto-generated catch block throw e ;}} /*** delete all, with no limit * @ param s Ql * @ throws SQLException */public void deleteall (String SQL) throws SQLException {try (PreparedStatement pStatement = conn. prepareStatement (SQL);) {pStatement.exe cuteUpdate ();} catch (SQLException e) {// TODO Auto-generated catch block throw e ;}} /*** unrestricted search * @ param SQL * @ param t generic class T. class * @ return ArrayList <T> * @ throws SQLException */public <T> ArrayList <T> select (String SQL, Class <T> T) throws SQLException {Method [] declaredMethods = t. getDeclaredMethods (); ArrayList <T> arrayList = new ArrayList <> (); try (PreparedStatement pStatement = conn. prepareStatement (SQL);) {try (ResultSet rSet=pStatement.exe cuteQuery ();) {ResultSetMetaData rData = rSet. getMetaData (); int columnCount = rData. getColumnCount (); while (rSet. next () {T a = t. newInstance (); for (int I = 0; I <columnCount; I ++) {Strin G aString = "set" + rData. getColumnName (I + 1); for (Method method: declaredMethods) {if (method. getName (). equalsIgnoreCase (aString) {method. setAccessible (true); method. invoke (a, rSet. getObject (I + 1); break ;}} arrayList. add (a) ;}} catch (InstantiationException e) {// TODO Auto-generated catch block e. printStackTrace ();} catch (IllegalAccessException e) {// TODO Auto-generated catch block e. pr IntStackTrace ();} catch (IllegalArgumentException e) {// TODO Auto-generated catch block e. printStackTrace ();} catch (InvocationTargetException e) {// TODO Auto-generated catch block e. printStackTrace () ;}} catch (SQLException e) {// TODO Auto-generated catch block throw e;} return arrayList ;} /*** number of data rows in the returned table * @ param tableName database table name * @ return number of rows * @ throws SQLException */public int count (S Tring tableName) throws SQLException {String SQL = "select count (*) from" + tableName; try (PreparedStatement pStatement = conn. prepareStatement (SQL); ResultSet rsset1_pstatement.exe cuteQuery ();) {if (rsSet. next () {return rsSet. getInt (1) ;}} catch (SQLException e) {// TODO Auto-generated catch block throw e;} return 0 ;} /*** determine whether data exists * @ param SQL has a placeholder? The SQL statement * @ param params replaces the placeholder data, and the dynamic array * @ return boolean * @ throws SQLException */public boolean isExist (String SQL, Object... params) throws SQLException {try (PreparedStatement pStatement = conn. prepareStatement (SQL);) {for (int I = 0; I <params. length; I ++) {pStatement. setObject (I + 1, params [I]);} try (ResultSet rsset1_pstatement.exe cuteQuery ();) {if (rsSet. next () {return true ;}} finally {}} catch (S QLException e) {// TODO Auto-generated catch block throw e;} return false ;} /*** create an instance ** @ param url Database url * @ param username * @ param password * @ return consql object * @ throws SQLException */public static Consql getnewInstance (String url, string username, String password) throws SQLException {if (consql = null) consql = new Consql (url, username, password); return consql;} // garbage collection, it seems that the Destructor cannot be achieved. Protected void finalize () throws Throwable {if (conn! = Null) {conn. close () ;}super. finalize ();}}

The above is a detailed explanation of the examples of JDBC database links and related method encapsulation. If you have any questions, please leave a message or go to the community on this site for discussion. Thank you for reading this article and hope to help you, thank you for your support!

Related Article

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.