利用
JDBC
鏈接
MySql
數據庫
在個人平常工做中幾乎每一個程序都要鏈接數據庫,爲了避免寫大量的重複的鏈接數據庫的代碼,我將鏈接封裝到一個類中。這樣能夠調用該類,填入適當的數據庫參數對數據庫進行鏈接,而後再做一系列的查詢(選擇)和更新(插入、刪除、更新)操做。下面是我封裝的類的一個簡化版本。
/** */
/**
* 數據庫操做
*/
package
database;
![](http://static.javashuo.com/static/loading.gif)
import
java.sql.Connection;
import
java.sql.DriverManager;
import
java.sql.ResultSet;
import
java.sql.Statement;
import
java.util.ArrayList;
import
java.util.HashMap;
import
java.util.Map;
![](http://static.javashuo.com/static/loading.gif)
![](http://static.javashuo.com/static/loading.gif)
/** */
/**
* @author Qutr
*
*/
public
class
DbConnection
![](http://static.javashuo.com/static/loading.gif)
...
{
private Connection dbConnection = null;
private Statement selectPro = null; //用於 select 操做
private Statement updatePro = null; //用於 update 操做
private ResultSet dbResultSet = null; //操做 select 結果集
private String driverName;//聲明MySql驅動類
private String dbHost;
private String dbPort;
private String dbName;
private String dbUserName;
private String dbPassword;
private String enCoding;
![](http://static.javashuo.com/static/loading.gif)
/** *//**
* 實例化DbConnection對象
* @param host 數據庫主機(IP)
* @param port 數據庫端口
* @param dName 數據庫名稱
* @param uName 用戶名
* @param password 用戶密碼
*/
public DbConnection(String host, String port, String dName, String uName, String password)
![](http://static.javashuo.com/static/loading.gif)
...{
driverName = "com.mysql.jdbc.Driver";
dbHost = host;
dbPort = port;
dbName = dName;
dbUserName = uName;
dbPassword = password;
enCoding = "?useUnicode=true&characterEncoding=gb2312&autoReconnect=true";
}//end DbConnection(...)
![](http://static.javashuo.com/static/loading.gif)
/** *//**
* 鏈接數據庫
* @return 鏈接成功返回true,鏈接失敗返回false
*/
public boolean dbConnection()
![](http://static.javashuo.com/static/loading.gif)
...{
StringBuilder urlTem = new StringBuilder();
urlTem.append("jdbc:mysql://");
urlTem.append(dbHost);
urlTem.append(":");
urlTem.append(dbPort);
urlTem.append("/");
urlTem.append(dbName);
urlTem.append(enCoding);
String url = urlTem.toString();
try
![](http://static.javashuo.com/static/loading.gif)
...{
Class.forName(driverName).newInstance();
dbConnection = DriverManager.getConnection(url, dbUserName, dbPassword);
return true;
![](http://static.javashuo.com/static/loading.gif)
}catch(Exception e)...{
System.err.println("數據庫聯接失敗!");
System.out.println("url = " + url);
e.printStackTrace(); //獲得詳細的出錯消息
return false;
}
}// end dbConnection()
![](http://static.javashuo.com/static/loading.gif)
/** *//**
* 執行專門的select操做,注意:在selectSql中的字段和fields中的個數、名稱要保持一致
* @param selectSql 用於執行的select語句
* @param fields 要選擇的字段
* @return 含有Map的ArrayList,一條記錄造成一個Map
*/
public ArrayList dbSelect(String selectSql, ArrayList fields)
![](http://static.javashuo.com/static/loading.gif)
...{
ArrayList<Map> selectResult = new ArrayList<Map>();
Map<String, String> recordInfo;
![](http://static.javashuo.com/static/loading.gif)
try...{
selectPro = dbConnection.createStatement();//定義Statement對象
dbResultSet = selectPro.executeQuery(selectSql);
![](http://static.javashuo.com/static/loading.gif)
while(dbResultSet.next())...{
recordInfo = new HashMap<String, String>();
for(int i = 0; i<fields.size(); ++i)
recordInfo.put((String)fields.get(i), dbResultSet.getString((String)fields.get(i)));
selectResult.add(recordInfo);
}
dbResultSet.close(); //斷開結果集
selectPro.close(); //斷開Statement對象
![](http://static.javashuo.com/static/loading.gif)
}catch(Exception e)...{
System.out.println("選擇操做失敗");
System.out.println("Sql = " + selectSql);
e.printStackTrace();
}
return selectResult;
}//end dbSelect(...)
![](http://static.javashuo.com/static/loading.gif)
/** *//**
* 對數據庫執行update,delete或insert操做
* @param sql 要執行操做的SQL語句
* @return 執行成功返回true,失敗返回false
*/
public boolean dbUpdate(String sql)
![](http://static.javashuo.com/static/loading.gif)
...{
try
![](http://static.javashuo.com/static/loading.gif)
...{
updatePro = dbConnection.createStatement(); //定義Statement對象
updatePro.executeUpdate(sql);
updatePro.close();// -------------關閉Statement對象
return true;
![](http://static.javashuo.com/static/loading.gif)
}catch(Exception err)...{
System.out.println("數據庫操做失敗!");
System.out.println("Sql = " + sql);
err.printStackTrace();
return false;
}
}//end dbUpdate(...)
![](http://static.javashuo.com/static/loading.gif)
/** *//**
* 關閉數據庫鏈接
* @return 成功返回true, 失敗返回false
*/
public boolean closeDatabase()
![](http://static.javashuo.com/static/loading.gif)
...{
![](http://static.javashuo.com/static/loading.gif)
try...{
if(dbConnection != null)
dbConnection.close();
return true;
![](http://static.javashuo.com/static/loading.gif)
}catch (Exception ex)...{
ex.printStackTrace();
return false;
}
}//end closeDatabase()
public static void main(String[] args)
![](http://static.javashuo.com/static/loading.gif)
...{
String dbHost = "localhost";
String dbPort = "3306";
String dbName = "test";
String dbUserName = "root";
String dbPassword = "";
DbConnection conn = new DbConnection(dbHost, dbPort, dbName, dbUserName, dbPassword);
boolean bool = conn.dbConnection();
if(!bool)
return;
String selectSql = "select user_name, ad from user_info where age = 23";
ArrayList<String> fieldsList = new ArrayList<String>();
fieldsList.add("user_name");
fieldsList.add("ad");
ArrayList<Map> userInfoList = conn.dbSelect(selectSql, fieldsList);
int infoSize = userInfoList.size();
String userName;
String ad;
if(infoSize == 0)
System.out.println("沒有選出符合條件的數據");
![](http://static.javashuo.com/static/loading.gif)
else...{
![](http://static.javashuo.com/static/loading.gif)
for(int i = 0; i < infoSize; ++i)...{
userName = (String)userInfoList.get(i).get("user_name");
ad = (String)(((Map)userInfoList.get(i)).get("ad"));
System.out.println("userName = " + userName + " ad = " + ad);
}
}
}//end main(...)
conn.closeDatabase();
![](http://static.javashuo.com/static/loading.gif)
}
//
end calss DbConnection
最後的結果:
userName =
張三 ad = 北京
userName =
趙一 ad = 上海
userName =
錢二 ad = 深圳
這個類很是簡單的實現了數據庫的通常操做,初學者能夠參考學習一下。將
DbConnection
中的
driverName
和數據庫的驅動更換之後能夠鏈接其餘數據庫。