Complete implementation of JdbcUtils, a jdbc framework class encapsulated by Java for MySql (including adding, deleting, and _ MySQL)

Source: Internet
Author: User
Using Java's complete implementation of the jdbc framework class JdbcUtils for MySql (including addition, deletion, modification, query, and JavaBean reflection principles, with the source code), I recently watched Lao Luo's video, followed by a framework class JdbcUtils that uses Java to operate MySql databases. java to add, delete, modify, and query databases. Query this part, including common query and utilization ReflectionThe completed query mainly includes the following function interfaces:

1. public Connection getConnection () obtain the database Connection 2. public boolean updateByPreparedStatement (String SQL, List3, public Map4, public List
 
  

The above four functions have included all MySQl operations, fully meeting the needs of use. In the video, Luo also extended two reflection functions for query.

5. public

6. public

The complete code is provided below:

JdbcUtils. java

Package com. jdbc. dbutils; import java. lang. reflect. field; import java. SQL. connection; import java. SQL. driverManager; import java. SQL. preparedStatement; import java. SQL. resultSet; import java. SQL. resultSetMetaData; import java. SQL. SQLException; import java. util. arrayList; import java. util. hashMap; import java. util. list; import java. util. map; import domain. userInfo; public class JdbcUtils {// database username private static Final String USERNAME = "root"; // database PASSWORD private static final String PASSWORD = "yanzi"; // DRIVER information private static final String DRIVER = "com. mysql. jdbc. driver "; // database address private static final String URL =" jdbc: mysql: // localhost: 3306/mydb "; private Connection connection; private PreparedStatement pstmt; private ResultSet resultSet; public JdbcUtils () {// TODO Auto-generated constructor stubtry {Class. forName (DRIV ER); System. out. println ("database connection successful! ");} Catch (Exception e) {}}/*** get Database Connection * @ return */public connection getConnection () {try {Connection = DriverManager. getConnection (URL, USERNAME, PASSWORD);} catch (SQLException e) {// TODO Auto-generated catch blocke. printStackTrace ();} return connection ;} /*** add, delete, and modify * @ param SQL * @ param params * @ return * @ throws SQLException */public boolean updateByPreparedStatement (String SQL, Listparams) th Rows SQLException {boolean flag = false; int result =-1; pstmt = connection. prepareStatement (SQL); int index = 1; if (params! = Null &&! Params. isEmpty () {for (int I = 0; i0? True: false; return flag;}/*** query a single record * @ param SQL * @ param params * @ return * @ throws SQLException */public MapfindSimpleResult (String SQL, Listparams) throws SQLException {Mapmap = new HashMap (); int index = 1; pstmt = connection. prepareStatement (SQL); if (params! = Null &&! Params. isEmpty () {for (int I = 0; I
   
    
FindModeResult (String SQL, Listparams) throws SQLException {List
    List = new ArrayList(); Int index = 1; pstmt = connection. prepareStatement (SQL); if (params! = Null &&! Params. isEmpty () {for (int I = 0; I
      
       
List = jdbcUtils. findModeResult (sql2, null); System. out. println (list); * // query a single record using reflection String SQL = "select * from userinfo where username =? "; Listparams = new ArrayList (); params. add ("Li Si"); UserInfo userInfo; try {userInfo = jdbcUtils. findSimpleRefResult (SQL, params, UserInfo. class); System. out. print (userInfo);} catch (Exception e) {// TODO Auto-generated catch blocke. printStackTrace ();}}}
      
   

+ ---------- + ------------- + ------ + ----- + --------- + ---------------- +

Nvicat is created in advance:

Because two interfaces use reflection, the corresponding JavaBean UserInfo. java code is as follows:

package domain;import java.io.Serializable;public class UserInfo implements Serializable{/** *  */private static final long serialVersionUID = 1L;private int id;private String username;private String pswd;public UserInfo() {// TODO Auto-generated constructor stub}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPswd() {return pswd;}public void setPswd(String pswd) {this.pswd = pswd;}@Overridepublic String toString() {return "UserInfo [id=" + id + ", username=" + username + ", pswd="+ pswd + "]";}}

Note:

1. after installing mysql-connector-java-gpl-5.1.26.exe, you will find that the jar package cannot be found. In fact, the jar file is in the C:/Program Files/MySQL Connector J directory and has two jar packages:

Which one is OK. Create a new folder libs in the Java project, copy the mysql-connector-java-5.1.26-bin.jar, right-click add to build path and OK.

2.Aside from this framework class JdbcUtils. java, the general steps for database operations are as follows:

(1) connect to the database and load the DRIVER: Class. forName (DRIVER); Driver = "com. mysql. jdbc. DRIVER"; this is reflection !!

(2) using the user name and password and the database name to connect, this step is the real connection:

connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);

Where: String URL = "jdbc: mysql: // localhost: 3306/mydb ";

(3) compile an SQL statement. Which of the following parameters is used? And then write the parameters to the List.

Run pstmt = connection. prepareStatement (SQL). then, extract the parameter from the list and fill it in pstmt.

(4) for addition, deletion, and modification: result = pstmt.exe cuteUpdate (); the result indicates the number of rows in the affected database, that is, several records. If the query is executed: resultSet = pstmt.exe cuteQuery (); The Returned type is ResultSet. Then, the resultSet is converted to Map or List.

3. for the query operation, use getMetaData to obtain the structure information of the table after the resultSet is obtained, such as how many columns are obtained by getColumnCount. String cols_name = metaData. getColumnName (I + 1); get the attribute name of each column, such as id, username, or pswd. and then from the Object cols_value = resultSet. getObject (cols_name); get it and put it in Map or List

4. perform the reflection operations in the query as follows:

(1) T resultObject = cls. newInstance (); use the newInstance () method of the class file to create an instance.

(2) after obtaining the number of columns through getColumnCount (), enter the loop,

String cols_name = metaData.getColumnName(i+1);

Read the attribute names and values of each column. Reflection by attribute name cols_name: Field field = cls. getDeclaredField (cols_name. setAccessible (true); // enable the access permission of javabean. in the set method, assign the cols_value obtained from the database to the set method of the JavaBean class, that is, the defined UserInfo. Field. set (resultObject, cols_value );

5.In general, the following steps are required to use Java reflection:

(1) load the Class object. There are two methods: Class cls1 = UserInfo. class or

Class cls2 = Class. forName ("domain. UserInfo") the latter uses the package name + Class name method.

(2) what will happen after reflecting out the Class? A class is similar to a constructor, a member variable, or a member function. So you can do these three things after getting the Class.

A,ConstructorTo obtain the Constructor, there are four methods:

Constructor getConstructor(Class[] params)Constructor[] getConstructors()Constructor getDeclaredConstructor(Class[] params)Constructor[] getDeclaredConstructors()

If no parameter is set, all constructors are obtained and a set is obtained. If a specific parameter is input, the system looks for this specific constructor. if Declared is not included, the public is obtained, and if Declared is included, the private constructor can be obtained. After obtaining the constructor, you can use reflection to create an instance:

Constructor con1[] = cls1.getDeclaredConstructors();

B. aboutMember variablesThere are also four methods:

Public Field getDeclaredField (String name) gets a member of any specified name

The JdbcUtils class encapsulated in this article is to use this method to operate private member variables in the class. remember to enable setAccessible. As follows:

Field field = cls.getDeclaredField(cols_name);

C. aboutMember functionsThere are also four methods:

Public Method [] getMethods () gets a set of all common methods

Parameter 1: method name parameter 2: set of parameter types

The following is a completed reflection example written using the UserInfo class in this article. the setUsername (String username) method is obtained and then reflected. Get the getUsername () method, then reflect it, and print the result:

Class clcs = UserInfo.class;

Method f = clcs. getDeclaredMethod ("setUsername", String. class); the type of input parameters in the original function. class. for example, if the original setXXX parameter needs to be input, the String is written during reflection. class.

6. JavaBean is a type of reflection. reflection has no requirements on constructor and so on. JavaBean requires that this class must inherit Serializable to be Serializable. In addition, the constructor must be public.In addition, JavaBean can directly call set and get after obtaining a field, without the need to obtain the method and then execute it.

Finally, reflection is performed when the program is running, not during compilation !!!

Reference: Link 1 link 2 link 3

The above is the complete implementation of the jdbc framework class JdbcUtils encapsulated by Java for MySql (including the content of addition, deletion, and MySQL). For more information, see The PHP Chinese network (www.php1.cn )!

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.