1 5 package org.h2.samples; 6 7 import java.sql.Connection ; 8 import java.sql.DriverManager ; 9 import java.sql.PreparedStatement ; 10 import java.sql.SQLException ; 11 import java.sql.Statement ; 12 13 import org.h2.api.DatabaseEventListener; 14 import org.h2.jdbc.JdbcConnection; 15 16 public class ShowProgress implements DatabaseEventListener { 17 18 private long last, start; 19 20 public ShowProgress() { 21 start = last = System.currentTimeMillis(); 22 } 23 24 public static void main(String [] args) throws Exception { 25 new ShowProgress().test(); 26 } 27 28 void test() throws Exception { 29 Class.forName("org.h2.Driver"); 30 Connection conn = DriverManager.getConnection("jdbc:h2:test;LOG=2", "sa", ""); 31 Statement stat = conn.createStatement(); 32 stat.execute("DROP TABLE IF EXISTS TEST"); 33 stat.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR)"); 34 PreparedStatement prep = conn.prepareStatement("INSERT INTO TEST VALUES(?, 'Test' || SPACE(100))"); 35 long time; 36 time = System.currentTimeMillis(); 37 int len = 1000; 38 for(int i=0; i<len; i++) { 39 long last = System.currentTimeMillis(); 40 if(last > time+1000) { 41 time = last; 42 System.out.println("Inserting " + (100L*i/len) + "%"); 43 } 44 prep.setInt(1, i); 45 prep.execute(); 46 } 47 boolean abnormalTermination = true; 48 if(abnormalTermination) { 49 ((JdbcConnection)conn).setPowerOffCount(1); 50 try { 51 stat.execute("INSERT INTO TEST VALUES(-1, 'Test' || SPACE(100))"); 52 } catch(SQLException e) { 53 } 54 } else { 55 conn.close(); 56 } 57 58 System.out.println("Open connection..."); 59 time = System.currentTimeMillis(); 60 conn = DriverManager.getConnection("jdbc:h2:test;LOG=2;DATABASE_EVENT_LISTENER='" + getClass().getName() + "'", "sa", ""); 61 time = System.currentTimeMillis() - time; 62 System.out.println("Done after " + time + " ms"); 63 conn.close(); 64 65 } 66 67 public void diskSpaceIsLow(long stillAvailable) throws SQLException { 68 System.out.println("diskSpaceIsLow stillAvailable="+stillAvailable); 69 } 70 71 public void exceptionThrown(SQLException e) { 72 e.printStackTrace(); 73 } 74 75 public void setProgress(int state, String name, int current, int max) { 76 long time = System.currentTimeMillis(); 77 if(time < last+5000) { 78 return; 79 } 80 last = time; 81 String stateName = "?"; 82 switch(state) { 83 case STATE_SCAN_FILE: 84 stateName = "Scan " + name; 85 break; 86 case STATE_CREATE_INDEX: 87 stateName = "Create Index " + name; 88 break; 89 case STATE_RECOVER: 90 stateName = "Recover"; 91 break; 92 } 93 try { 94 Thread.sleep(1); 95 } catch (InterruptedException e) { 96 } 97 System.out.println("State: " + stateName + " " + (100*current/max) + "% (" + current+" of " + max + ") " + (time-start)+" ms"); 98 } 99 100 public void closingDatabase() { 101 System.out.println("Closing the database"); 102 } 103 104 public void init(String url) { 105 System.out.println("Initializing the event listener for database " + url); 106 } 107 108 } 109 | Popular Tags |