資源簡介
寫好sql語句,調(diào)用該工具類內(nèi)的方法,即可實現(xiàn)增刪改查mysql數(shù)據(jù)庫的操作。帶有詳細(xì)解釋
代碼片段和文件信息
package?db;
/*
?*?To?change?this?license?header?choose?License?Headers?in?Project?Properties.
?*?To?change?this?template?file?choose?Tools?|?Templates
?*?and?open?the?template?in?the?editor.
?*/
import?com.sun.rowset.CachedRowSetImpl;
import?java.sql.*;
import?javax.sql.rowset.CachedRowSet;
/**
?*
?*?@author?Administrator
?*/
public?class?DBUtil?{
static?String?_url?=?“jdbc:mysql://localhost:3306/test“;
static?String?_username?=?“root“;
static?String?_password?=?“root“;
????//按傳入的SQL進行數(shù)據(jù)庫查詢操作
????@SuppressWarnings(“finally“)
public?static?CachedRowSet?querySQL(String?sql)?throws?SQLException?{
????????//離線集合
????????CachedRowSet?crs?=?new?CachedRowSetImpl();
????????//定義數(shù)據(jù)庫連接對象·Connection.???定義傳輸對象.???定義結(jié)果集對象
????????Connection?conn?=?null;
????????Statement?stmt?=?null;
????????ResultSet?rs?=?null;
????????try?{
????????????//加載Driver驅(qū)動
????????????Class.forName(“com.mysql.jdbc.Driver“);
????????????//創(chuàng)建數(shù)據(jù)庫連接對象connection??localhost:3306分別為本機ip和數(shù)據(jù)庫接入端口號
????????????conn?=?DriverManager.getConnection(_url?_username?_password);
????????????//創(chuàng)建一個可向數(shù)據(jù)庫發(fā)送SQL命令并返回結(jié)果的傳送對象
????????????stmt?=?conn.createStatement();
????????????//將sql命令通過sql傳送對象傳送到數(shù)據(jù)庫執(zhí)行
????????????rs?=?stmt.executeQuery(sql);
????????????//處理結(jié)果集
????????????crs.populate(rs);
????????}?catch?(Exception?ex)?{
????????????ex.printStackTrace();
????????}?finally?{
????????????//手動關(guān)閉資源
????????????if?(rs?!=?null)?{
????????????????try?{
????????????????????rs.close();
????????????????}?catch?(Exception?ex)?{
????????????????????ex.printStackTrace();
????????????????}
????????????}
????????????if?(stmt?!=?null)?{
????????????????try?{
????????????????????stmt.close();
????????????????}?catch?(Exception?ex)?{
????????????????????ex.printStackTrace();
????????????????}
????????????}
????????????if?(conn?!=?null)?{
????????????????try?{
????????????????????conn.close();
????????????????}?catch?(Exception?ex)?{
????????????????????ex.printStackTrace();
????????????????}
????????????}
????????????return?crs;
????????}
????}
????//按傳入的SQL進行數(shù)據(jù)庫更新操作(單條、無事務(wù))
????@SuppressWarnings(“finally“)
public?static?boolean??updateSQL(String?sql)?{
????????boolean?rtn?=?false;
????????//定義數(shù)據(jù)庫連接對象·Connection定義傳輸對象
????????Connection?conn?=?null;
????????Statement?stmt?=?null;
????????try?{
????????????//加載Driver驅(qū)動
????????????Class.forName(“com.mysql.jdbc.Driver“);
????????????//創(chuàng)建數(shù)據(jù)庫連接對象connection
????????????conn?=?Driver
評論
共有 條評論