/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.util;
import Java.io.UnsupportedEncodingException;
import Java.sql.*;
/**
*
* @author swing
*/
public class DbUtility {
private Connection conn = null;
private ResultSet set = null;
private Statement st = null;
// 數據庫連接使用的參數;
private String DBUrl = "jdbc:MySQL://localhost/acctest?useUnicode=true&characterEncoding=gbk";
//這裡使用編碼就可以解決MySQL中文問題,其他得不需要設置
private String DBUser = "root";// 用戶名
private String DBPass = "root";// 密碼
private String DBDriver = "org.gjt.mm.mysql.Driver";// MySQL驅動
public DbUtility() {
}
//獲取數據庫連接
public Connection getAConnection(String DBDriver, String DBUrl, String DBUser, String DBPass) {
try {
Class.forName(DBDriver).newInstance();
} catch (Exception e) {
System.out.println("沒有安裝MySQL Java Connector或類路徑未設置正確: " + e);
return null;
}
try {
conn = DriverManager.getConnection(DBUrl, DBUser, DBPass);
} catch (SQLException e) {
System.out.println("com.util.DbUtility.getAConnection:數據庫錯誤: " + e);
return null;
}
return conn;
}
//insert or update table
public boolean execute(String sql) throws UnsupportedEncodingException {
conn = getAConnection(DBDriver, DBUrl, DBUser, DBPass);
if (conn == null) {
System.out.println("連接數據庫失敗");
return false;
}
try {
st = conn.createStatement();
st.execute(sql);
st.close();
conn.close();
conn = null;
} catch (SQLException e) {
System.out.println("database error:" + e.getMessage());
return false;
}
return true;
}
/**
* Description : 執行查詢語句
*
* @param sql
* sql查詢語句
* @return set ResultSet形式的查詢結果,
*/
public ResultSet query(String sql) {
// 建立連接
conn = getAConnection(DBDriver, DBUrl, DBUser, DBPass);
if (conn == null) {
System.out.println("連接數據庫失敗");
return null;
}
try {
st = conn.createStatement();
return st.executeQuery(sql);
} catch (SQLException e) {
System.out.println("database error:" + e.getMessage());
return null;
}
}
/**
* Description : 調用查詢語句後關閉連接
*
* @return 1 成功關閉連接
*/
public int close() {
try {
if (set != null) {
set.close();
}
if (st != null) {
st.close();
}
if (conn != null) {
conn.close();
}
return 1;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
}