时间:2021-07-01 10:21:17 帮助过:7人阅读
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;