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 Staticlist<object> Query (class<?>obj) {Statement St=NULL; List<Object> list=NewArraylist<>(); //the address of the database MySQLString dburl= "Jdbc:mysql://localhost:3306/lms_leave?useunicode=true&characterencoding=utf-8"; String DBName= "Root";//Log In User nameString dbpwd= "123456";//Log in Password//Load Driver Try{class.forname ("Com.mysql.jdbc.Driver"); //connecting to a databaseConnection conn=drivermanager.getconnection (DBURL,DBNAME,DBPWD); //Create a statement objectst=conn.createstatement (); ResultSet RS=st.executequery ("SELECT * from" +obj.getsimplename ()); //get the methods in the passed-in classMethod[] Methods=Obj.getmethods (); //sets a list of methods, in which the method is placed in order to invoke theList<method> list_m=NewArraylist<>(); //There are many methods in the class that filter out some methods to get the method you want for(inti=0;i<methods.length;i++) {//Filtration Method//determine if there is a set in the name of the method to extract if(Methods[i].getname (). Contains ("Set")) { //add a method to the listList_m.add (Methods[i]); } } //creates a string collection of strings, and gets the following field names to depositList<string> fieldname=NewArraylist<>(); //gets the properties in the class whose properties correspond to the fields in the databaseField[] F=Obj.getdeclaredfields (); //Loop capitalizes the first name in a field for(inti = 0; i < f.length; i++) { //Get the nameString field=F[i].getname (); //variable case, deposited into FieldName collectionFieldname.add (Uppercase (field)); } //gets the structure of the resulting set (RS), such as the number of fields, field names, and so on. ResultSetMetaData rsmd=Rs.getmetadata (); //iterating through the data in the result set to the list collection while(Rs.next ()) {//Create an incoming class object userObject user=obj.newinstance (); //a collection of traversal methods for(Method m:list_m) {//iterating through a collection of fields for(inti = 0; i < f.length; i++) { //method and field to see if the method name contains the field name, matching if(M.getname (). Contains ("Set" +Fieldname.get (i))) { //match success, then go to get rsmd to get the field name in the database, Rs.getobject, and then according to get this field name to get this field valueObject Value=rs.getobject (Rsmd.getcolumnname (i+1)); //get the type of this field in order to store the type of this valueClass<?> type=F[i].gettype (); //is a conversion of type int if(type==int.class) {Value=NewInteger (value.tostring ()); } //Conversion of String type if(type==string.class) {Value=value.tostring (); } //m is a method in the user object that sets its valuem.invoke (user, value); } } } //adds a User object instance to the list collectionlist.add (user); } } Catch(Exception e) {//TODO auto-generated Catch blockE.printstacktrace (); } returnlist; }
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 to 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 additions and deletions to the general method