Learn from the original CSDN author yanzi1225627 an article: http://blog.csdn.net/yanzi1225627/article/details/26950615
The author of the writing is very good, he used the time to make a little modification, the change is the parameter file and close the connection function. The modified section is marked in red
Jdbcutils.java
The modified code is as follows:
/** * Created by Administrator on 2017-12-08. */import java.io.ioexception;import java.io.inputstream;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.*;p ublic class JdbcUtils {//database user name Private Static String USERNAME; Database Password private static String PASSWORD; Driver information private static String DRIVER; Database address private static String URL; Private Connection Connection; Private PreparedStatement pstmt; Private ResultSet ResultSet; Parameterless constructor, the parameter is out of the configuration file public jdbcutils () {//Use the parameter file method to judge the database connection, Config.properties file in the same directory Jdbcutil.java file, such as my Java file in the Src folder, Config.properties also in the src folder inputstream InputStream = g Etclass (). getResourceAsStream ("config.properties"); Properties P = new properties (); try {p.load (InputStream); } catch (IOException E1) {e1.printstacktrace (); } DRIVER = P.getproperty ("DRIVER"); url = p.getproperty ("url"); USERNAME = P.getproperty ("USERNAME"); PASSWORD = P.getproperty ("PASSWORD");//System.out.println ("URL:" +p.getproperty ("url") + ", USERNAME:" +p.getproperty ("USERNAME") + ", PASSWORD:" +p.getproperty ("PASSWORD")); try{Class.forName (DRIVER); SYSTEM.OUT.PRINTLN ("Database connection succeeded! "); }catch (Exception e) {}}/** * get connection to Database * @return */public Connection getconnection () { try {connection = Drivermanager.getconnection (URL, USERNAME, PASSWORD); } catch (SQLException e) {//TODO auto-generated catch block E.printstacktrace (); } return connection; }/** * Add, delete, change * @param SQL * @param params * @return * @throws SQLException */public bool EAN updatebypreparedstatement (String sql, List<object>params) throws sqlexception{Boolean flag = false; int result =-1; pstmt = connection.preparestatement (sql); int index = 1; if (params! = null &&!params.isempty ()) {for (int i=0; i<params.size (); i++) {pstmt.se TObject (index++, Params.get (i)); }} result = Pstmt.executEupdate (); Flag = result > 0? True:false; return flag; }/** * Query a single record * @param SQL * @param params * @return * @throws SQLException */Public MAP&L T String, object> Findsimpleresult (String sql, list<object> params) throws sqlexception{map<string, Obje ct> map = new hashmap<string, object> (); int index = 1; pstmt = connection.preparestatement (sql); if (params! = null &&!params.isempty ()) {for (int i=0; i<params.size (); i++) {pstmt.se TObject (index++, Params.get (i)); }} ResultSet = Pstmt.executequery ();//Return query result resultsetmetadata MetaData = Resultset.getmetadata (); int col_len = Metadata.getcolumncount (); while (Resultset.next ()) {for (int i=0; i<col_len; i++) {String cols_name = Metadata.getcolumn Name (i+1); Object Cols_value = Resultset.getobject (cols_name); if (Cols_value = = null) {Cols_value = ""; } map.put (Cols_name, Cols_value); }} return map; }/** Query multiple records * @param SQL * @param params * @return * @throws SQLException */Public list<map& Lt String, object>> Findmoderesult (String sql, list<object> params) throws sqlexception{List<map<st Ring, object>> list = new arraylist<map<string, object>> (); int index = 1; pstmt = connection.preparestatement (sql); if (params! = null &&!params.isempty ()) {for (int i = 0; I<params.size (); i++) {pstmt. SetObject (index++, Params.get (i)); }} ResultSet = Pstmt.executequery (); ResultSetMetaData metaData = Resultset.getmetadata (); int cols_len = Metadata.getcolumncount (); while (Resultset.next ()) {map<string, object> Map = new Hashmap< String, object> (); for (int i=0; i<cols_len; i++) {String cols_name = Metadata.getcolumnname (i+1); Object Cols_value = Resultset.getobject (cols_name); if (Cols_value = = null) {Cols_value = ""; } map.put (Cols_name, Cols_value); } list.add (map); } return list; /** queries a single record by reflection mechanism * @param SQL * @param params * @param cls * @return * @throws Exception */ Public <T> T Findsimplerefresult (String sql, list<object> params, CLASS&L T T> cls) throws exception{T resultobject = null; int index = 1; pstmt = connection.preparestatement (sql); if (params! = null &&!params.isempty ()) {for (int i = 0; I<params.size (); i++) {pstmt. SetObject (index++, Params.get (i)); }} ResultSet = Pstmt.execuTequery (); ResultSetMetaData metaData = Resultset.getmetadata (); int cols_len = Metadata.getcolumncount (); while (Resultset.next ()) {//Creates an instance by reflection mechanism Resultobject = cls.newinstance (); for (int i = 0; i<cols_len; i++) {String cols_name = Metadata.getcolumnname (i+1); Object Cols_value = Resultset.getobject (cols_name); if (Cols_value = = null) {Cols_value = ""; } Field field = Cls.getdeclaredfield (Cols_name); Field.setaccessible (TRUE); Open JavaBean access Rights Field.set (Resultobject, Cols_value); }} return resultobject; /** queries multiple records by reflection mechanism * @param SQL * @param params * @param cls * @return * @throws Exception */ Public <T> list<t> Findmorerefresult (String sql, list<object> params, Class<t> cls) throws Exception {list<t> List = new arraylist<t> (); int index = 1; pstmt = connection.preparestatement (sql); if (params! = null &&!params.isempty ()) {for (int i = 0; I<params.size (); i++) {pstmt. SetObject (index++, Params.get (i)); }} ResultSet = Pstmt.executequery (); ResultSetMetaData metaData = Resultset.getmetadata (); int cols_len = Metadata.getcolumncount (); while (Resultset.next ()) {//Creates an instance by reflection mechanism T Resultobject = Cls.newinstance (); for (int i = 0; i<cols_len; i++) {String cols_name = Metadata.getcolumnname (i+1); Object Cols_value = Resultset.getobject (cols_name); if (Cols_value = = null) {Cols_value = ""; } Field field = Cls.getdeclaredfield (Cols_name); Field.setaccessible (TRUE); Open JavaBean access rights Field.set (ResulTObject, Cols_value); } list.add (Resultobject); } return list; }/** * Free database connection */public void Releaseconn () {if (ResultSet! = null) {try{R Esultset.close (); }catch (SQLException e) {e.printstacktrace (); } } }/** * Closes all resources, the result set object is closed in Releaseconn in the original code and is not released for Preparestatement and connection. */private void CloseAll () {//Close result set object if (ResultSet! = null) {try {Resultse T.close (); } catch (SQLException e) {System.out.println (E.getmessage ()); }}//Close the PreparedStatement object if (pstmt! = null) {try {pstmt.close (); } catch (SQLException e) {System.out.println (E.getmessage ()); }}//Close the Connection object if (connection! = null) {try {connection.close (); } catch (SQLException e) {System.out.println (E.getmessage ()); } } } /** * @param args */public static void main (string[] args) throws SQLException {//TODO Auto-gener Ated method Stub Jdbcutils jdbcutils = new Jdbcutils (); Jdbcutils.getconnection (); Jdbcutils.closeall (); /******************* *********************//* String sql = "INSERT into UserInfo (username, pswd) values (?, ?), (?, ?), (?, ?)"; list<object> params = new arraylist<object> (); Params.add ("Xiao Ming"); Params.add ("123xiaoming"); Params.add ("Zhang San"); Params.add ("Zhangsan"); Params.add ("John Doe"); Params.add ("lisi000"); try {Boolean flag = jdbcutils.updatebypreparedstatement (sql, params); SYSTEM.OUT.PRINTLN (flag); } catch (SQLException e) {//TODO auto-generated catch block E.printstacktrace (); }*//******************* Delete *********************///remove record named Zhang San/* String sql = "Delete from UseriNFO where username =? "; list<object> params = new arraylist<object> (); Params.add ("Xiao Ming"); Boolean flag = jdbcutils.updatebypreparedstatement (sql, params); *//******************* change *********************/ Change the password with the name John Doe */* String sql = "Update userinfo set pswd =?" where username =? "; list<object> params = new arraylist<object> (); Params.add ("lisi88888"); Params.add ("John Doe"); Boolean flag = jdbcutils.updatebypreparedstatement (sql, params); SYSTEM.OUT.PRINTLN (flag); *//******************* check *********************///Do not use reflection to query multiple records/* String SQL2 = "SELECT * from UserInfo"; list<map<string, object>> list = Jdbcutils.findmoderesult (SQL2, NULL); SYSTEM.OUT.PRINTLN (list); */}}
config.properties file as follows, modify the library parameters that you want to connect to it.
DRIVER = Com.mysql.jdbc.DriverURL = Jdbc:mysql://localhost:3307/testusername = Mainpassword = QWERTASDFG
Please contact me if you do not understand or write the wrong place. q1163949417
JDBC Encapsulation (using a parameter file)