Java Connection MySQL Database additions and deletions change general method operating environment: Eclipse+mysql
Before we Java connection MySQL database is a database to write a class, under the class to write a lot of methods, if multiple databases, it is necessary to write more than one class of methods, resulting in code is too cumbersome, so in order to change this cumbersome, I will connect the database method of a series of encapsulation, By passing the user an object value, object can get the desired.
I have written a common Java connection MySQL database, you can see, so that the comparison of the reference to know the gap between the database--mysql-->java
Next I will tell you how to use this non-reusable, and many duplicate connection code, encapsulated, very useful
Basic idea:
When we connect to the database, the method of writing is to write a class, one of the countless methods, the connection database is required:
- Class.forName (): Load Driver--"com.mysql.jdbc.Driver
- Drivermanager.getconnection (): drive management, connecting to a database three properties 1. Database Address 2. Database user name 3. password
- Createstatement (): Create statement Object
- ResultSet: Execute SQL statement to get result set, then traverse
So we have to be universal, then the database name, SQL statements, the result set to traverse the results to be obtained, according to the different database according to the parameters of the change
First, each project starts with the database manifested, each table is an entity class, the table name is the class name, the field is its property, and the set and get methods are used for these properties
Then according to the reflection mechanism, the object is the instantiation object of our table, according to the parameter object that I pass in the method, get the method, property, attribute value, type and so on a series of things, to implement the method encapsulation Universal
Code Demo
First, a query is shown: by passing in the entity class of this table, by a series of radiation mechanisms, the comparison is assembled into a query method
public static list<object> query (Class<?> obj) {Statement st=null; List<object> list=new arraylist<> (); Database MySQL address String dburl= "Jdbc:mysql://localhost:3306/lms_leave?useunicode=true&characterencoding=utf -8 "; String dbname= "root"; Login username String dbpwd= "123456";//Login password//load drive try {CLASS.FO Rname ("Com.mysql.jdbc.Driver"); Connection Database Connection conn=drivermanager.getconnection (DBURL,DBNAME,DBPWD); Create statement Object St=conn.createstatement (); ResultSet rs=st.executequery ("select * from" +obj.getsimplename ()); Gets the method passed in the class method[] Methods=obj.getmethods (); Sets the List collection of a method, in which the method is placed so that the list<method> list_m= new arraylist<> () is called; There are many methods in the class that filter some methods to get the method you want for (int i=0;i<methods. length;i++) {///filter method//Determine if the method name has set this extract if (Methods[i].getname (). Contains ("set")) { Add method to List List_m.add (Methods[i]); }}//Create string collection of strings, get the following field names in List<string> fieldname=new arraylist< > (); Gets the properties in the class whose properties correspond to fields in the database field[] F=obj.getdeclaredfields (); The loop capitalizes the first name in the field for (int i = 0; i < f.length; i++) {//Get name Strin G Field=f[i].getname (); Variable case, deposited fieldname set Fieldname.add (Uppercase (field)); }//Get the structure of the result set (RS), such as the number of fields, field names, etc. ResultSetMetaData rsmd= rs.getmetadata (); Iterates through the data in the result set to the list collection while (Rs.next ()) {//creates an incoming class object user object us Er=obj.newinstance ();The collection of traversal methods for (method M:list_m) {//Iterate the collection of fields for (int i = 0; i < f.length; i++) {//Method and field for comparison, see if the method name contains this field name, both match if (M.getname (). Contains ("Set +fieldname.get (i)) {///match succeeded, then go to get rsmd to get the field name in the database, Rs.getobject, and then get this field value according to the field name obtained Object Value=rs.getobject (Rsmd.getcolumnname (i+1)); Get the type of this field in order to store the type of this value class<?> type=f[i].gettype (); is an int type of conversion if (Type==int.class) {value=new Integer (VA Lue.tostring ()); }//string type of conversion if (Type==string.class) { Value=value.tostring (); } M is a method in the user object that sets its value m.invoke (user, value); }}}//To add the User object instance to the list collection List.add (US ER); }} catch (Exception e) {//TODO auto-generated catch block e.prints Tacktrace (); } return list; }
You can refer to this method can be completely modified into the remaining insert, modify, delete
Let's give you a hint. The insertion method encapsulates the important point of getting the field that you want to insert, which can be done by stitching the INSERT statement into a complete SQL statement.
M.invoke (user); My understanding is to run the method m under the user class and get the return value Object Object=m.invoke (user);
These things need to think more about their own summary, I hope that useful to everyone, I do not write more, leaving everyone a little space for thinking, need the rest of the way packaging can leave a message to tell me
Java Connection MySQL Database