📄 datastore.java
字号:
package bit.jeffy.db;
import java.sql.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/*
* 创建日期 2005-4-7
*
* TODO 要更改此生成的文件的模板,请转至
* 窗口 - 首选项 - Java - 代码样式 - 代码模板
*/
/**
* @author jeffy522
*
* TODO 要更改此生成的类型注释的模板,请转至 窗口 - 首选项 - Java - 代码样式 - 代码模板
*/
public class DataStore {
private static DataStore db = null;
private static Connection conn = null;
private Statement stmt = null;
private boolean hadErrors = false;
private DataStore() throws Exception {
if (conn == null) {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "root",
"1");
stmt = conn.createStatement();
}
}
public void beginTransaction() throws SQLException
{
conn.setAutoCommit(false);
}
public void commitTransaction() throws SQLException
{
if( !hadErrors ){
conn.commit();
}
else{
conn.rollback();
hadErrors = false;
}
hadErrors = false;
conn.setAutoCommit(true);
}
public void ErrorOccur( ){
hadErrors = true;
}
public static DataStore getInstance() {
if (db == null) {
try {
db = new DataStore();
} catch (Exception e) {
conn = null;
Log log = LogFactory.getLog("mylog");
log.error("数据库连接出错-DataStore.java");
return null;
}
}
return db;
}
synchronized public void execute(String sql){
try{
if (stmt != null)
stmt.executeUpdate(sql);
else {
Log log = LogFactory.getLog("mylog");
log.error("数据库插入数据出错");
}
}catch(SQLException e){
}
}
synchronized public ResultSet read(String sql){
ResultSet tmp = null;
try{
if (stmt != null) {
tmp = stmt.executeQuery(sql);
return tmp;
} else {
return null;
}
}catch(SQLException e){
return null;
}
}
synchronized public int readCount( String sql ){
int nCount = 0;
try {
if( stmt != null ) {
ResultSet tmp = null;
tmp = stmt.executeQuery(sql);
if( tmp!=null && tmp.next() ) {
nCount = tmp.getInt(1);
}else {
nCount = 0;
}
}else {
nCount = 0;
}
}catch(SQLException e) {
nCount = 0;
}
return nCount;
}
synchronized public void stop() {
try {
if (conn != null) {
conn.close();
stmt.close();
}
} catch (Exception e) {
/* 记录到日志 */
Log log = LogFactory.getLog("mylog");
log.error("数据库关闭出错-DataStore.java");
} finally {
conn = null;
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -