操作数据库的一个DB类

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

 

 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;
}
 
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值