Home > Back-end >  Java JDBC - tools
Java JDBC - tools

Time:10-27

/*
* need to load the driver package import database
* is not the original according to the original author to https://me.csdn.net/weixin_42404323? Ref=miniprofile
*/
Public class jdbcUtil {
/*
* static load mysql drivers drive package
* */
The static {
Try {
Class.forName("com.mysql.jdbc.Driver");
} the catch (a ClassNotFoundException e) {
//TODO Auto - generated the catch block,
e.printStackTrace();
}
}

/*
* create a connection object
*/
Public static Connection getConnection () throws SQLException {
The String url="JDBC: mysql://localhost: 3306/stuDB? UseUnicode=true& CharacterEncoding=utf8 ";//links
String user="root";//user name
String password="123456";//password
Return DriverManager. GetConnection (url, user, password);
}

/*
* close to add deletion operation connection object
*/
Public static void Close (Connection coon, PreparedStatement STMT) {
If (STMT!=null) {
Try {
STMT. Close ();
Coon. Close ();
} the catch (SQLException e) {
//TODO Auto - generated the catch block,
e.printStackTrace();
}
}
}
/*
* close reading connection object
*/
Public static void Close (Connection coon, PreparedStatement STMT, ResultSet rs) {
If (rs!=null) {
Try {
Rs. The close ();
STMT. Close ();
Coon. Close ();
} the catch (SQLException e) {
//TODO Auto - generated the catch block,
e.printStackTrace();
}
}
}
/*

* increase deletion operation method* String SQL execution increase bowdlerize SQL statement
* Object [] parems operation parameter
*/
Public static int NonQuery (String, SQL Object [] parems) {
The Connection coon=null;
PreparedStatement STMT=null;
Int the rowCount=0;
Try {
Coon=getConnection ();
STMT=coon. PrepareStatement (SQL);
If (parems!=null& & Parems. Length> 0 {
For (int I=0; i STMT. SetObject (I + 1, parems [I]);
}
}
RowCount=STMT. ExecuteUpdate ();
} the catch (SQLException e) {
//TODO Auto - generated the catch block,
e.printStackTrace();
} the finally {
Close (coon, STMT);
}
Return the rowCount;
}

/*
* generic query
* String SQL execution increase bowdlerize SQL statement
* Object [] parems operation parameter
* RowsMapper Rm custom generic class field read interface -- entity class information
*/
Public static ArrayList GenericQeruy (String SQL Object [] parems, RowsMapper The rm) {
The Connection coon=null;
PreparedStatement STMT=null;
ResultSet rs=null;
ArrayList List=new ArrayList (a);
Try {
Coon=getConnection ();
STMT=coon. PrepareStatement (SQL);
If (parems!=null& & Parems. Length> 0 {
For (int I=0; i STMT. SetObject (I + 1, parems [I]);
}
}
Rs=STMT. ExecuteQuery ();
While (rs), next ()) {
T T=rm. GetEntity (rs);
List. Add (t);
}
} the catch (SQLException e) {
//TODO Auto - generated the catch block,
e.printStackTrace();
} the finally {
Close (coon, STMT, rs);
}
return list;
}
}

CodePudding user response:

code deep foundation
  • Related