1 30 31 32 package org.hsqldb.sample; 33 34 import java.sql.Connection ; 35 import java.sql.DriverManager ; 36 import java.sql.ResultSet ; 37 import java.sql.ResultSetMetaData ; 38 import java.sql.SQLException ; 39 import java.sql.Statement ; 40 41 51 public class Testdb { 52 53 Connection conn; 55 public Testdb(String db_file_name_prefix) throws Exception { 58 Class.forName("org.hsqldb.jdbcDriver"); 61 62 conn = DriverManager.getConnection("jdbc:hsqldb:" 69 + db_file_name_prefix, "sa", ""); } 73 74 public void shutdown() throws SQLException { 75 76 Statement st = conn.createStatement(); 77 78 st.execute("SHUTDOWN"); 82 conn.close(); } 84 85 public synchronized void query(String expression) throws SQLException { 87 88 Statement st = null; 89 ResultSet rs = null; 90 91 st = conn.createStatement(); 93 rs = st.executeQuery(expression); 97 dump(rs); 99 st.close(); 101 } 107 108 public synchronized void update(String expression) throws SQLException { 110 111 Statement st = null; 112 113 st = conn.createStatement(); 115 int i = st.executeUpdate(expression); 117 if (i == -1) { 118 System.out.println("db error : " + expression); 119 } 120 121 st.close(); 122 } 124 public static void dump(ResultSet rs) throws SQLException { 125 126 ResultSetMetaData meta = rs.getMetaData(); 129 int colmax = meta.getColumnCount(); 130 int i; 131 Object o = null; 132 133 for (; rs.next(); ) { 139 for (i = 0; i < colmax; ++i) { 140 o = rs.getObject(i + 1); 142 System.out.print(o.toString() + " "); 144 } 145 146 System.out.println(" "); 147 } 148 } 150 public static void main(String [] args) { 151 152 Testdb db = null; 153 154 try { 155 db = new Testdb("db_file"); 156 } catch (Exception ex1) { 157 ex1.printStackTrace(); 159 return; } 161 162 try { 163 164 db.update( 169 "CREATE TABLE sample_table ( id INTEGER IDENTITY, str_col VARCHAR(256), num_col INTEGER)"); 170 } catch (SQLException ex2) { 171 172 } 179 180 try { 181 182 db.update( 185 "INSERT INTO sample_table(str_col,num_col) VALUES('Ford', 100)"); 186 db.update( 187 "INSERT INTO sample_table(str_col,num_col) VALUES('Toyota', 200)"); 188 db.update( 189 "INSERT INTO sample_table(str_col,num_col) VALUES('Honda', 300)"); 190 db.update( 191 "INSERT INTO sample_table(str_col,num_col) VALUES('GM', 400)"); 192 193 db.query("SELECT * FROM sample_table WHERE num_col < 250"); 195 196 db.shutdown(); 198 } catch (SQLException ex3) { 199 ex3.printStackTrace(); 200 } 201 } } 204 | Popular Tags |