importjava.io.*;
importjava.util.*;
public classconnDB {
publicConnectionconn =null;
publicStatementstmt =null;
publicResultSetrs =null;
private staticStringpropFileName ="connDB.properties";
private staticPropertiesprop =newProperties();
private staticStringpath =Thread.currentThread().getContextClassLoader().getResource("").getPath();
private staticStringdbClassName =
"com.microsoft.jdbc.sqlserver.SQLServerDriver";
private staticStringdbUrl ="";
private staticStringdbUser ="sa";
private staticStringdbPwd ="";
private static voidloadProperty() {
try{
prop.load(newFileInputStream(path+"/"+propFileName));//通过文件输入流对象加载Properties文件
dbClassName = prop.getProperty("DB_CLASS_NAME");
dbUrl = prop.getProperty("DB_URL");
dbUser = prop.getProperty("DB_USER");
dbPwd = prop.getProperty("DB_PWD");
}
catch(Exceptione) {
e.printStackTrace();
}
}
public staticConnectiongetConnection() {
Connectionconn =null;
loadProperty();
try{
Class.forName(dbClassName).newInstance();
conn =DriverManager.getConnection(dbUrl, dbUser, dbPwd);
}
catch(Exceptionee) {
ee.printStackTrace();
}
if(conn ==null) {
System.err.println(
"警告: DbConnectionManager.getConnection() 获得数据库链接失败.\r\n\r\n链接类型:"+
dbClassName +"\r\n链接位置:"+ dbUrl +"\r\n用户/密码"+ dbUser +"/"+
dbPwd);
}
returnconn;
}
publicResultSetexecuteQuery(Stringsql) {
try{
conn =getConnection();
stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
rs = stmt.executeQuery(sql);
}
catch(SQLExceptionex) {
System.err.println(ex.getMessage());
}
returnrs;
}
public intexecuteUpdate(Stringsql) {
intresult= 0;
try{
conn =getConnection();
stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
result= stmt.executeUpdate(sql);
}
catch(SQLExceptionex) {
result= 0;
}
try{
stmt.close();
}
catch(SQLExceptionex1) {
}
returnresult;
}
public intexecuteUpdate_id(Stringsql) {
intresult= 0;
try{
conn =getConnection();
stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
result= stmt.executeUpdate(sql);
StringID ="select @@IDENTITY as id";
rs = stmt.executeQuery(ID);
if(rs.next()) {
intautoID = rs.getInt("id");
result= autoID;
}
}
catch(SQLExceptionex) {
result= 0;
}
returnresult;
}
public voidclose() {
try{
if(rs !=null) {
rs.close();
}
}
catch(Exceptione) {
e.printStackTrace(System.err);
}
try{
if(stmt !=null) {
stmt.close();
}
}
catch(Exceptione) {
e.printStackTrace(System.err);
}
try{
if(conn !=null) {
conn.close();
}
}
catch(Exceptione) {
e.printStackTrace(System.err);
}
}
}