/*
*匯入資料庫需要加載的驅動包
*不是原創 根據原作者所改https://me.csdn.net/weixin_42404323?ref=miniprofile
*/
public class jdbcUtil {
/*
* 靜態驅動加載 mysql驅動包
* */
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*
* 創建連接物件
*/
public static Connection getConnection() throws SQLException {
String url="jdbc:mysql://localhost:3306/stuDB?useUnicode=true&characterEncoding=utf8";//鏈接地址
String user="root";//用戶名
String password="123456";//密碼
return DriverManager.getConnection(url, user, password);
}
/*
* 關閉增刪改操作的連接物件
*/
public static void Close(Connection coon,PreparedStatement stmt) {
if (stmt!=null) {
try {
stmt.close();
coon.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/*
* 關閉讀取連接物件
*/
public static void Close(Connection coon,PreparedStatement stmt,ResultSet rs) {
if (rs!=null) {
try {
rs.close();
stmt.close();
coon.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/*
* 增刪改操作的方法
* String sql 執行增刪改的SQL陳述句
* Object[] parems 操作引數
*/
public static int NonQuery(String sql,Object[] parems) {
Connection coon = null;
PreparedStatement stmt = null;
int rowCount = 0;
try {
coon = getConnection();
stmt = coon.prepareStatement(sql);
if (parems!=null&&parems.length>0) {
for (int i = 0; i < parems.length; i++) {
stmt.setObject(i+1, parems[i]);
}
}
rowCount = stmt.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
Close(coon,stmt);
}
return rowCount;
}
/*
* 泛型查詢
* String sql 執行增刪改的SQL陳述句
* Object[] parems 操作引數
* RowsMapper<T> rm 自定義泛型類 欄位讀取介面 --獲取物體類資訊
*/
public static<T> ArrayList<T> GenericQeruy(String sql,Object[] parems,RowsMapper<T> rm){
Connection coon = null;
PreparedStatement stmt = null;
ResultSet rs = null;
ArrayList<T> list = new ArrayList<T>();
try {
coon = getConnection();
stmt = coon.prepareStatement(sql);
if (parems!=null&&parems.length>0) {
for (int i = 0; i < parems.length; i++) {
stmt.setObject(i+1, parems[i]);
}
}
rs = stmt.executeQuery();
while(rs.next()) {
T t = rm.getEntity(rs);
list.add(t);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
Close(coon, stmt, rs);
}
return list;
}
}
uj5u.com熱心網友回復:
代碼功底深厚
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/192741.html
標籤:Eclipse
