1, the previous mentioned FindByID (int id), just an operation for the user table, in order to make the lookup method more general, introduced the generics and reflection
2. Use generics and reflection to make the public static <T> T FindByID (class<t> clazz, int id) method more general. Genericityjdbcutils's code is as follows
Package com.jdbc.genericity.utils;
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.sql.Statement;
Import java.util.Properties;
Import Com.jdbc.entity.User;
Import Com.jdbc.utils.MyJDBCUtils;
public class Genericityjdbcutils {private static Connection conn;
private static PreparedStatement pstate;
private static ResultSet Rs;
For better decoupling of the program, use the properties file to save the configuration file connected to MySQL private static Properties config = new properties (); /** * uses the static block to load the database's configuration file and the database's driver/static {try {Config.load (MyJDBCUtils.class.getClassLoader (). Getresourceas
Stream ("db.properties"));
Class.forName (Config.getproperty ("Driver"));
catch (Exception e) {throw new Exceptionininitializererror (e); }/** * Get a connection to a database * * @return/public static Connection getconnection () {Connection conn = null; try {conn = Drivermanager.getconnection (config.getproperty ("url"), Config.getproperty ("username"), config.ge
Tproperty ("password"));
catch (SQLException e) {throw new RuntimeException ("Get connection to MySQL database connection failed");
Return conn; /** * FREE Database connection * * @param conn * @param St * @param rs/public static void release (Connection conn, St
Atement St, ResultSet rs) {if (rs!= null) {try {rs.close ();
catch (Exception e) {throw new RuntimeException ("ResultSet shutdown exception");
rs = null;
} if (St!= null) {try {st.close ();
catch (Exception e) {throw new RuntimeException ("Statement shutdown exception");
} st = null;
} if (conn!= null) {try {conn.close ();
catch (Exception e) {throw new RuntimeException ("Connection shutdown exception");
} conn = null; }/** * * * @param clazz * BYTE code * @param ID of the type to be returned * to find the ID of the record in the table * @return Find in the database To the record, and return */public static;
T> T FindByID (class<t> clazz, int id) {T bean = null;
System.out.println (Clazz.getsimplename ());
try {bean = clazz.newinstance ();
String tablename = Clazz.getsimplename ();
String sql = "SELECT * from" + tablename + "WHERE id =?";
conn = getconnection ();
pstate = conn.preparestatement (sql);
Pstate.setint (1, id);
rs = Pstate.executequery ();
if (Rs.next ()) {//ResultSetMetaData MetaData = Rs.getmetadata () of the array of result sets)
int count = Metadata.getcolumncount (); for (int i = 0; i < count; i++) {//Note jdbc subscript, starting from 1//To get the name of the column in the database String name = Metadata.getcolumnnam
E (i + 1);
Gets, the database column corresponds to the numeric Object value = rs.getobject (name);
The property Field f = Bean.getclass (). Getdeclaredfield (name) on the reflection bean that is the same as the column name;
F.setaccessible (TRUE);
F.set (bean, value);
} return bean;
catch (Exception e) {throw new RuntimeException ("in the database, find the user record with ID + ID +" failed. "+ e); finally {//release resources, closeConnection to the database release (conn, pstate, RS); }/** * Based on incoming SQL statements to the table records of the new database * * @param SQL * @param args/public static void update (String sql, OBJ
Ect[] {(Args.length < 0) {throw new RuntimeException ("object[] args array length, should not be empty") {try {args);
} conn = getconnection ();
pstate = conn.preparestatement (sql);
for (int i = 0; i < args.length i++) {pstate.setobject (i + 1, args[i]);
}//Note to invoke this method Pstate.executeupdate ();
Releasing resources, shutting down the connection to the database release (conn, pstate, RS);
catch (Exception e) {throw new RuntimeException ("Failed to update record in database" + E); }/** * Update records in database tables according to SQL statements * @param SQL/public static void update (String sql) {try {conn = getc
Onnection ();
pstate = conn.preparestatement (sql);
Note To call this method Pstate.executeupdate ();
Releasing resources, shutting down the connection to the database release (conn, pstate, RS);
catch (Exception e) {throw new RuntimeException ("Failed to update record in database" + E);
}
}
}
3, the test code is as follows
Package com.jdbc.genericity.test;
Import Org.junit.Test;
Import Com.jdbc.entity.Person;
Import Com.jdbc.entity.User;
Import Com.jdbc.genericity.utils.GenericityJDBCUtils;
public class Genericityjdbcutilstest {
@Test public
void Tenericityjdbcutilstest () {
User user = Genericityjdbcutils.findbyid (User.class, 1);
SYSTEM.OUT.PRINTLN (user);
Person person = Genericityjdbcutils.findbyid (Person.class, 1);
SYSTEM.OUT.PRINTLN (person);
}
3, the situation of the database
4, the results of the program operation are as follows