现在的位置: 首页 > 综合 > 正文

操作数据库的一个DB类

2014年03月03日 ⁄ 综合 ⁄ 共 1677字 ⁄ 字号 评论关闭

这个类使用起来很方便,而且也较安全一些。欢迎大家提意见。

 

 package cn.ijser.utils;

 
import java.io.File;
import java.sql.*;
 
import com.mysql.jdbc.Statement;
 
public class DB {
String dbUrl = "";
String dbPort = "";
String dbName = "";
String dbUser = "";
String dbPass = "";
private static Connection conn = null;
private static String tablePrefix;
 
public DB() {
try {
/* 获取配置文件 */
File cfgUrl = FilePathUtil.getFileByRelativePath("/config.properties");
Configuration cfg = new Configuration(cfgUrl.toString());
dbUrl = cfg.getValue("DatabaseUrl", "localhost");
dbPort = cfg.getValue("DatabasePort", "3306");
dbName = cfg.getValue("DatabaseName", "kexie51");
dbUser = cfg.getValue("DatabaseUserName", "kexie51");
dbPass = cfg.getValue("DatabasePassword", "kexie51");
DB.tablePrefix = cfg.getValue("TablePrefix", "kx_");
} catch (ConfigurationException e) {
e.printStackTrace();
}
}
 
public PreparedStatement prepare(String sql) {
PreparedStatement ps = null;
 
try {
/* 获得Connection */
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://" + dbUrl + ":"
+ dbPort + "/" + dbName, dbUser, dbPass);
ps = conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
 
return ps;
}
 
@Override
protected void finalize() throws Throwable {
System.out.println("db connection closed...");
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn = null;
}
super.finalize();
}
 
public void close(PreparedStatement stmt) {
try {
if (stmt != null) {
stmt.close();
stmt = null;
}
if (conn != null) {
conn.close();
conn = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
 
public void close(ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs = null;
}
}
 
public String getTablePrefix() {
return tablePrefix;
}
 
}

抱歉!评论已关闭.