/*
* 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;
}
}
}