1 16 package dlog4j.hsqldb; 17 18 import java.io.File ; 19 import java.sql.Connection ; 20 import java.sql.DriverManager ; 21 import java.sql.PreparedStatement ; 22 import java.sql.ResultSet ; 23 24 import org.hsqldb.Server; 25 26 30 public class HSQLEngine { 31 32 private static HSQLEngine engine; 33 private static Server hsqldb; 34 35 private HSQLEngine(){} 36 45 public synchronized static HSQLEngine getEngine(String dataPath, int port, String dbn) 46 { 47 if(engine!=null) 48 return engine; 49 HSQLEngine engine = new HSQLEngine(); 50 if(!dataPath.endsWith(File.separator)) 51 dataPath += File.separator; 52 hsqldb = new Server(); 53 if(port>0) 54 hsqldb.setPort(port); 55 if (dbn != null){ 56 hsqldb.setDatabaseName(0, dbn); 57 dataPath+=dbn; 58 } 59 hsqldb.setDatabasePath(0, dataPath); 60 61 hsqldb.setSilent(true); 62 hsqldb.setTrace(false); 63 return engine; 64 } 65 66 public void start(){ 67 hsqldb.start(); 69 } 70 71 public void stop(){ 72 hsqldb.stop(); 73 int i=0; 74 while(i<10 && isRunning()){ 75 i++; 76 try{ 77 Thread.sleep(500); 78 }catch(Exception e){} 79 } 80 } 81 82 public boolean isRunning(){ 83 try{ 84 hsqldb.checkRunning(true); 85 return true; 86 }catch(RuntimeException e){ 87 return false; 88 } 89 } 90 91 public String getDatabaseName() { 92 return hsqldb.getDatabaseName(0,false); 93 } 94 95 public String getDataPath() { 96 return hsqldb.getDatabasePath(0,false); 97 } 98 99 public int getPort() { 100 return hsqldb.getPort(); 101 } 102 103 public static void main(String [] args) throws Exception { 104 HSQLEngine engine = HSQLEngine.getEngine("D:\\TEST",9001,null); 105 engine.start(); 106 try{ 107 testCreateTable(); 108 }finally{ 109 engine.stop(); 110 } 111 } 112 113 public static void testCreateTable() throws Exception { 114 Class.forName("org.hsqldb.jdbcDriver"); 115 Connection conn = DriverManager.getConnection("jdbc:hsqldb:hsql://localhost","sa",""); 116 PreparedStatement ps = null; 117 ResultSet rs = null; 118 try{ 119 122 ps = conn.prepareStatement("SELECT * FROM dlog_user"); 123 rs = ps.executeQuery(); 124 while(rs.next()){ 125 System.out.println(rs.getString("displayName")); 126 } 127 }finally{ 128 if(rs!=null) 129 rs.close(); 130 if(ps!=null) 131 ps.close(); 132 if(conn!=null) 133 conn.close(); 134 } 135 } 136 137 } | Popular Tags |