import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Map;
public class Sqlconnect {
public Connection dbConn = null;
public Statement stmt;
public PreparedStatement st = null;
boolean autoCommit;
public ResultSet rs = null;
public String sql = null;
public String driverName = "";
public String dbURL = "";
public String userName = "";
public String userPwd = "";
//连接数据库
public SQLconnect() {
init();
}
//初始化数据库
public void init() {
try {
Map<String,String> map= InitialConf.getXmlMap();
driverName = map.get("DBdriverName");
dbURL = map.get("DBurl");
userName = map.get("DBuserName");
userPwd = map.get("DBuserPwd");
Class.forName(driverName);
dbConn = DriverManager.getConnection(dbURL, userName, userPwd);
} catch (Exception e) {
e.printStackTrace();
}
}
public static SQLconnect getNewInstance() {
return new SQLconnect();
}
//开启事务
public void beginTrans() throws SQLException {
try {
autoCommit = dbConn.getAutoCommit();
dbConn.setAutoCommit(false);
} catch (SQLException ex) {
throw ex;
}
}
//事务提交
public void commit() throws SQLException {
try {
dbConn.commit();
dbConn.setAutoCommit(autoCommit);
} catch (SQLException ex) {
throw ex;
}
}
//事务回滚
public void rollback() {
try {
dbConn.rollback();
dbConn.setAutoCommit(autoCommit);
} catch (SQLException ex) {
ex.printStackTrace();
}
}
//自动提交
public boolean getAutoCommit() throws SQLException {
boolean result = false;
try {
result = dbConn.getAutoCommit();
} catch (SQLException ex) {
throw ex;
}
return result;
}
</pre><pre code_snippet_id="353403" snippet_file_name="blog_20140519_10_5766327" name="code" class="java">//查询
public ResultSet executeQuery(String sql) throws SQLException {
ResultSet rs = null;
try {
stmt = dbConn.createStatement();
rs = stmt.executeQuery(sql);
} catch (SQLException ex) {
throw ex;
}
return rs;
}
</pre><pre code_snippet_id="353403" snippet_file_name="blog_20140519_10_5766327" name="code" class="java">//更新,c插入,删除
public int executeUpdate(String sql) throws SQLException {
try {
stmt = dbConn.createStatement();
return stmt.executeUpdate(sql);
} catch (SQLException ex) {
throw ex;
}
}
</pre><pre code_snippet_id="353403" snippet_file_name="blog_20140519_10_5766327" name="code" class="java">//关闭数据库连接
public void close() throws SQLException {
try {
if (stmt != null) {
stmt.close();
stmt = null;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (dbConn != null)
dbConn.close();
} catch (SQLException e) {
e.printStackTrace();
throw e;
}
}
}
}