java 簡單的H2數據庫工具類
package db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.h2.tools.DeleteDbFiles;
public class DbUtil {
private static Connection myConnection = null;
static {
try {
Class.forName("org.h2.Driver");
} catch (ClassNotFoundException ex) {
Logger.getLogger(DbUtil.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void setupConn(String theDbPath) throws SQLException {
if(null == myConnection || myConnection.isClosed()) {
myConnection = DriverManager.getConnection("jdbc:h2:"+theDbPath);
}
}
public static Statement getStatement() throws SQLException {
if(null==myConnection || myConnection.isClosed()) {
SQLException ex = new SQLException("No valid database connection!");
Logger.getLogger(DbUtil.class.getName()).log(Level.SEVERE, null, ex);
throw ex;
}
return myConnection.createStatement();
}
public static void closeConn() throws SQLException {
myConnection.close();
}
public static void setupDB(String theDbPath) throws SQLException {
setupConn(theDbPath);
runScript("init.sql");
}
public static void runScript(String thePath) throws SQLException {
Statement stat = getStatement();
stat.execute("runscript from '"+thePath+"'");
stat.close();
}
public static void resetDB(String theDbPath) throws Exception {
// to separate the dbname from the path
int lastSlash = theDbPath.lastIndexOf('/');
DeleteDbFiles.execute(theDbPath.substring(0,lastSlash),
theDbPath.substring(lastSlash),
true);
setupDB(theDbPath);
}
}
本文由用戶 xuanxu11 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!