Article From:https://www.cnblogs.com/MyJavaStudy/p/9215318.html

Custom a simple JDBC framework, including add, modify, delete, query methods, add, delete, simple incoming SQL and (prepareStatement) precompilation is required parameters, in this example, the use of variable parameters, through the following, through the followingThe code sets the parameters required for precompilation. The query method encapsulates the results of the query into one corresponding object and returns the object back to list.

 

 // Setting parametersParameterMetaData parameterMetaData = stmt.getParameterMetaData ();InT count = parameterMetaData.getParameterCount ();For (int i = 1; I < = count; i++) {Stmt.setObject (I, obj[i - 1]);}Stmt.execute ();

  The main method of query is to encapsulate the result set into javaBean.

  

1      The result set metadata ResultSetMetaData result set metadata is obtained by using rs.getMetaData ().

        ResultSetMetaData resultSetMetaData=rs.getMetaData();
2       Total number of columns
           int count =resultSetMetaData.getColumnCount();
3        The introspection technology acquisition class requests to be passed to the corresponding class.Class * /
BeanInfo beanInfo = Introspector.getBeanInfo(domainClass);
 4         Using introspection technology to get all the attributes in the class
    PropertyDescriptor[] propertyDescriptors=beanInfo.getPropertyDescriptors();

5       Ergodic result set

   《1》  Traversing all the columns

   《2》  Comparing all properties to each column, if the property name is the same as the column’s field name, the value of the column is assigned to the same property as the column name using the reflection technique.

 

Introspection:

  Introspection (Introspector) is the way Java language deals with attributes and events of JavaBean class.

  For example, if there are attributes name in class User, then there must be getName, setName method. We can get or set values through them. This is routine operation.

  JavaIt provides a set of API getter/setter methods to access an attribute, which are stored in java.beans.

Reflex:

  JavaThe reflection mechanism is to get all attributes and methods of this class for any class in operation.

  For any object, it can call any of its methods.

  This function of dynamically acquiring class information and dynamically calling class object methods is called the reflection mechanism of Java language.

 

 

 

			/*1   ResultSetMetaData Result set metadata - get result set name, number, type * /ResultSetMetaData resultSetMetaData=rs.getMetaData ();/*2 acquisitionTotal number * /Int count =resultSetMetaData.getColumnCount ();/*3 introspection technology gets class request to import corresponding class.Class * /BeanInfo beanInfo = Introspector.getBeanInfo (domainClass);/*4 gets all the attributes * /PropertyDescRiptor[] propertyDescriptors=beanInfo.getPropertyDescriptors ();/*5 traversal of the result set * /While (Rs.next ()) {/*< 1> get the generic instance object * /T t=domainClass.newInstance ();/*&lT; 2> traverses every field in the database to see if it matches the property name; if matching, place the field values in the database into attributes.For (int i=1; i< =count; i++) {/ / obtain column namesString columnName=resultSetMetaData.getColumnName (I);For (PropertyDescrIptor pd:propertyDescriptors) {* * attribute attribute is assigned to the attribute when it matches the name in the database * /If (columnName.Equals (pd.getName ())) {/*usernamePublic void com.goke.User.setUsername (java.lang.Stri)NG) pd.getWriteMethod ()UserpwdPublic void com.goke.User.setUserpwd (java.lang.String) pd.GetWriteMethod ()UserdescPublic void com.goke.User.setUserdesc (java.lang.String) pd.getWRiteMethod ()ID does not have a set method to show* * // / obtain the corresponding set methodMethod setMethod=pd.getWriteMethod ();SetMethod.invoke (T, new Object[]{rs.getObject (columnName)};}}}List.add (T);}

  

The detailed code is as follows:

package com.goke;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.rl.JDBCUtil;

public class JDBCIfram {

	public static void main(String[] args) {

		BeanHanderInterface<User> beanHander=new BeanHanderImpl<>(User.class);
		/*String sqlInsert="insert into user (username,userpwd) values(?,?)";
		Object [] obje={"liming","liming"};
		insert(sqlInsert, obje);
		String sql="delete from user where username=? and userpwd=?";
		//Object [] obj={"zhang","lei"};
		delete(sql, new Object[]{"zhang","lei"});
		
		*/
		
		String sql="select * from user";
		System.out.println(query(sql, beanHander, null));
		
		
	}
	
	
	/*Query * /Public static < T> List< T> query (String SQL, BeanHanderInterface< T> BeanHanderInterface<)R, Object... ARG) {T obj = null;List< T> list=new ArrayList< > ();ConnectionConn = null;PreparedStatement stmt = null;ResultSet rs = null;Try{Conn = JDBCUtil.getConnection ();Stmt = conn.prepareStatement (SQL);/ / setting parametersParameterMetaData parameterMetaData = stmt.getParameterMetaData ();Int count = parameterMetaData.getParameterCount ();For (int i = 1; I < =Count; i++) {Stmt.setObject (I, arg[i - 1]);}Rs = sTmt.executeQuery ();List = beanHander.hander (RS);} catch (SQLException E) {E.printStackTrace ();} finally {//JDBCUtil.colseREsource (Conn, stmt, RS);}Return list;}/ * insert * /Public static void insert (STring SQL, Object[] obj) {Connection conn = null;PreparedStatement stmt = null;ResultSet rs = null;Try {Conn = JDBCUtil.getConnection ();Stmt = conn.prepareStatement (SQL);/ / setting parametersParameterMetaData parametErMetaData=stmt.getParameterMetaData ();Int count =parameterMetaData.getParameterCount ();For (int i = 1; I < = count; i++) {Stmt.setObject (I, obj[i - 1]);}Stmt.executeUpdate ();} catch (SQLException E) {E.printStackTrace ();} finally {JDBCUtil.colseResource (Conn, stmt, RS);}}/ * modification * /Public static void update (String SQL, Object[] obj) {Connection conn =Null;PreparedStatement stmt = null;ResultSet rs = null;Try {Conn = JDBCUtil.getConnection ();Stmt = conn.prepareStatement (SQL);/ / setting parametersParameterMetaData parameterMetaData = stmt.getParameterMetaData ();Int count = parameterMetaData.getParameterCount ();For (int i = 1; I < = count;I++) {Stmt.setObject (I, obj[i - 1]);}Stmt.executeUpdaTe ();} catch (SQLException E) {E.printStackTrace ();} finally {JDBCUtil.colseResource (Conn, stmt, RS);}}/ * delete * /Public static VoID delete (String SQL, Object[] obj) {Connection conn = null;PreparedStatement stmt =Null;ResultSet rs = null;Try {Conn = JDBCUtil.getConnection ();Stmt = conn.prepareStatement (SQL);/ / setting parametersParameterMetaDATA parameterMetaData = stmt.getParameterMetaData ();Int count = parameterMetaData.getPArameterCount ();For (int i = 1; I < = count; i++) {Stmt.setObject (I, obj[i - 1]);}Stmt.execute ();} catch (SQLException E) {E.printStackTrace ();} finally {JDBCUtil.colseResource (Conn, stmt, R)S);}}}/ * create the interface that encapsulates the query result as entity class * /Interface BeanHanderInterface< T> {Public LisT< T> hander (ResultSet RS); / / the result set is encapsulated into T entity class.}/ * interface implementation class * /Class BeanHanderImpl< T> implemEnts BeanHanderInterface< T> {Private Class< T> domainClass;Public BeanHanderImpl (CLass< T> domainClass) {Super ();This.domainClass = domainClass;}@OverridePublic LiSt< T> hander (ResultSet RS) {List< T> list=new ArrayList< > ();Try {/*1 REsultSetMetaData result set metadata - get result set name, number, type * /ResultSetMetaData resultSetMetaData=rs.getMetaData ();/*2 get the total number of columns * /Int count =resultSetMetaData.getColumnCount ();/*3 introspection technology gets class request to import corresponding.Class.Class * /BeanInfo beanInfo = Introspector.getBeanInfo (domainClass);/*4 gets all the attributes * /PropertyDescriptor[] propertyDescriptors=beanInfo.getPropertyDescriptors ();/*5 traversal knotFruit set * /While (rs.next ()) {/*< 1> get the generic instance object * /T t=domainClass.newInstanCE ();/*< 2> traverses every field in the database to see if it matches the property name; if matching, place the field values in the database into attributes.For (int i=1; i<=count; i++) {/ / obtain column namesString columnName=resultSetMetaData.getColumnName (I);For (PropertyDescriptor pd:propertyDescriptors) {* * attribute attribute is assigned to the attribute when it matches the name in the database * /If (columnName.equals (pd.getName ())) {/*usernamePublic void com.goke.User.setUsernaMe (java.lang.String) pd.getWriteMethod ()UserpwdPublic void com.goke.User.setUserpwd (JAVA.lang.String) pd.getWriteMethod ()UserdescPublic void com.goke.User.setUserdesc (java.laNg.String) pd.getWriteMethod ()ID does not have a set method to show* * // / obtain the corresponding set methodMethod setMethod=pd.getWriteMethod ();SetMethod.invoke (T, new Object[]{rs.getObject)(columnName)});}}}List.add (T);}} catch (SQLException E) {/ / TODO Auto-generated catch blockE.printStackTrace ();} catch (IntrospectioNException E) {/ / TODO Auto-generated catch blockE.printStackTrace ();} catch (InstantiatiOnException E) {/ / TODO Auto-generated catch blockE.printStackTrace ();} catch (IllegalAccEssException E) {/ / TODO Auto-generated catch blockE.printStackTrace ();} catch (IllegalArGumentException E) {/ / TODO Auto-generated catch blockE.printStackTrace ();} catch (InvocaTionTargetException E) {/ / TODO Auto-generated catch blockE.printStackTrace ();}ReturnList;}}

  The addition, deletion, modification, and query methods are simply implemented in this column. In the query, the results are encapsulated into the class when the database fields and attribute names are the same, and the database fields and the attribute names are not handled differently, such as the database field is user_nameThe property field is username

 

Link of this Article: Handwritten simple JDBC

Leave a Reply

Your email address will not be published. Required fields are marked *