自己写的数据库封装,在使用时只需要使用query和update操作即可
package api.com.servlet;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class DBBean {
private static Connection con = null;
private static Statement stmt = null;
private static ResultSet rs = null;
private static boolean is_ready = false;
private static boolean is_driver_loaded = false;
private DBBean() {
}
private static void load() {
try {
Class.forName(StaticConfig.db_driver);
} catch (Exception e) {
System.err.println("DB Driver Load Error!");
is_driver_loaded = false;
}
is_driver_loaded = true;
}
private static void getReady() {
if (is_driver_loaded == false)
load();
if (is_driver_loaded == false) {
is_ready = false;
return;
}
try {
con = DriverManager.getConnection(StaticConfig.db_url,
StaticConfig.db_user, StaticConfig.db_password);
} catch (Exception e) {
System.err.println("DB Connection Fetch Error!");
con = null;
is_ready = false;
return;
}
is_ready = true;
}
public static ResultSet query(String sql) {
if (is_ready == false) {
getReady();
}
if (is_ready == false)
return null;
try {
stmt = con.createStatement();
} catch (Exception e) {
System.err.println("DB Statement Fetch Error!");
stmt = null;
return null;
}
try {
rs = stmt.executeQuery(sql);
} catch (Exception e) {
System.err.println("DB Query Error!");
rs = null;
}
return rs;
}
public static int update(String sql) {
if (is_ready == false) {
getReady();
}
if (is_ready == false)
return -1;
try {
stmt = con.createStatement();
} catch (Exception e) {
System.err.println("DB Statement Fetch Error!");
stmt = null;
return -1;
}
int inflenced_row = -1;
if (stmt == null) {
System.err.println("DB Statement Fetch Error!");
return -1;
}
try {
inflenced_row = stmt.executeUpdate(sql);
} catch (Exception e) {
System.err.println("DB Update Error!");
inflenced_row = -1;
}
return inflenced_row;
}
public void disconnect() {
try {
if (null == rs) {
rs.close();
}
if (null == stmt) {
stmt.close();
}
if (null == con) {
con.close();
}
} catch (Exception e) {
System.err.println("DB Resource Release Error!");
}
}
}
为了防止乱码可以指定读取的输入库的编码,修改如下
private static void getReady() {
if (is_driver_loaded == false)
load();
if (is_driver_loaded == false) {
is_ready = false;
return;
}
try {
Properties prop = new Properties();
prop.put("user", StaticConfig.db_user);
prop.put("password",StaticConfig.db_password);
prop.put("characterEncoding","GBK");
con = DriverManager.getConnection(StaticConfig.db_url,
prop);
} catch (Exception e) {
System.err.println("DB Connection Fetch Error!");
con = null;
is_ready = false;
return;
}
is_ready = true;
}