JDBC Database Operation code Template
PackageCom.oolong.util;Importjava.sql.Connection;ImportJava.sql.DriverManager;Importjava.sql.PreparedStatement;ImportJava.sql.ResultSet;ImportJava.sql.ResultSetMetaData;Importjava.sql.SQLException;Importjava.util.ArrayList;ImportJava.util.HashMap;Importjava.util.List;ImportJava.util.Map; Public classDBHelper {PrivateString drivername = "Com.mysql.jdbc.Driver"; PrivateString url = "Jdbc:mysql://localhost:3306/hrms?usessl=true"; PrivateString userName = "root"; PrivateString password = "1234"; PrivateConnection Conn; Private StaticDBHelper DBHelper; Public StaticConnection getconnection () {if(DBHelper = =NULL) {Dbhelper.dbhelper=NewDBHelper (); } returnDbhelper.conn; } PrivateDBHelper () {Try{class.forname (drivername); This. conn =drivermanager.getconnection (URL, userName, password); } Catch(ClassNotFoundException e) {e.printstacktrace (); } Catch(SQLException e) {e.printstacktrace (); } } Public Static intexecuteupdate (String sql, string[] param) {Connection conn=NULL; PreparedStatement PST=NULL; intres = 0; Try{conn=dbhelper.getconnection (); PST=conn.preparestatement (SQL); for(inti = 0; i < param.length; i++) {pst.setstring (i+1, Param[i]); } Res=pst.executeupdate (); Pst.close (); Conn.close (); } Catch(SQLException ex) {ex.printstacktrace (); } Catch(Exception e) {e.printstacktrace (); } returnRes; } Public StaticList<map<string, object>>executeQuery (String sql) {returnExecuteQuery (SQL,NewString[0]); } Public StaticList<map<string, object>>executeQuery (String sql, string[] param) {Connection conn=NULL; PreparedStatement PST=NULL; ResultSet RS=NULL; List<map<string, object>> Resut =NewArraylist<>(); Map<string, object> map =NULL; Try{conn=dbhelper.getconnection (); PST=conn.preparestatement (SQL); for(inti = 0; i < param.length; i++) {pst.setstring (i+1, Param[i]); } RS=Pst.executequery (); ResultSetMetaData RSM=Rs.getmetadata (); string[] Columns=NewString[rsm.getcolumncount ()]; for(inti = 0; I < Rsm.getcolumncount (); i++) {Columns[i]= Rsm.getcolumnname (i + 1); } rs.beforefirst (); while(Rs.next ()) {map=NewHashmap<>(); for(String col:columns) {map.put (col, Rs.getobject (col)); } resut.add (map); } rs.close (); Pst.close (); Conn.close (); } Catch(SQLException ex) {ex.printstacktrace (); } Catch(Exception e) {e.printstacktrace (); } returnResut; }}
Jdbc--dbhelper Code Templates