Posted By

studioevoque on 07/20/11


Tagged

database sql java


Versions (?)

Simple H2 Database utility class


 / Published in: Java
 

A simple utility class that uses the H2 SQL Db to maintain a database connection. It also gives a convenience method to run SQL scripts.

Note:The init.sql value is hardcoded, and should be replaced by a static variable if needed

  1. package db;
  2.  
  3. import java.sql.Connection;
  4. import java.sql.DriverManager;
  5. import java.sql.SQLException;
  6. import java.sql.Statement;
  7. import java.util.logging.Level;
  8. import java.util.logging.Logger;
  9. import org.h2.tools.DeleteDbFiles;
  10.  
  11. public class DbUtil {
  12. private static Connection myConnection = null;
  13.  
  14. static {
  15. try {
  16. Class.forName("org.h2.Driver");
  17. } catch (ClassNotFoundException ex) {
  18. Logger.getLogger(DbUtil.class.getName()).log(Level.SEVERE, null, ex);
  19. }
  20. }
  21.  
  22.  
  23. public static void setupConn(String theDbPath) throws SQLException {
  24. if(null == myConnection || myConnection.isClosed()) {
  25. myConnection = DriverManager.getConnection("jdbc:h2:"+theDbPath);
  26. }
  27. }
  28.  
  29. public static Statement getStatement() throws SQLException {
  30. if(null==myConnection || myConnection.isClosed()) {
  31. SQLException ex = new SQLException("No valid database connection!");
  32. Logger.getLogger(DbUtil.class.getName()).log(Level.SEVERE, null, ex);
  33. throw ex;
  34. }
  35.  
  36. return myConnection.createStatement();
  37. }
  38.  
  39. public static void closeConn() throws SQLException {
  40. myConnection.close();
  41. }
  42.  
  43. public static void setupDB(String theDbPath) throws SQLException {
  44.  
  45. setupConn(theDbPath);
  46. runScript("init.sql");
  47. }
  48.  
  49. public static void runScript(String thePath) throws SQLException {
  50.  
  51. Statement stat = getStatement();
  52. stat.execute("runscript from '"+thePath+"'");
  53. stat.close();
  54. }
  55.  
  56. public static void resetDB(String theDbPath) throws Exception {
  57. // to separate the dbname from the path
  58. int lastSlash = theDbPath.lastIndexOf('/');
  59.  
  60.  
  61. DeleteDbFiles.execute(theDbPath.substring(0,lastSlash),
  62. theDbPath.substring(lastSlash),
  63. true);
  64.  
  65. setupDB(theDbPath);
  66. }
  67.  
  68. }

Report this snippet  

You need to login to post a comment.