`
jiasudu1649
  • 浏览: 711242 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

hsqldb First JDBC Client Example

阅读更多
hsqldb自带的例子。看看就一切ok了,万事不求人啊。
There is a copy of Testdb.java in the directory src/org/hsqldb/sample of your HSQLDB distribution.

java 代码
 
  1.  1.  /* Copyright (c) 2001-2005, The HSQL Development Group  
  2.  2.  * All rights reserved.  
  3.  3.  *  
  4.  4.  * Redistribution and use in source and binary forms, with or without  
  5.  5.  * modification, are permitted provided that the following conditions are met:  
  6.  6.  *  
  7.  7.  * Redistributions of source code must retain the above copyright notice, this  
  8.  8.  * list of conditions and the following disclaimer.  
  9.  9.  *  
  10. 10.  * Redistributions in binary form must reproduce the above copyright notice,  
  11. 11.  * this list of conditions and the following disclaimer in the documentation  
  12. 12.  * and/or other materials provided with the distribution.  
  13. 13.  *  
  14. 14.  * Neither the name of the HSQL Development Group nor the names of its  
  15. 15.  * contributors may be used to endorse or promote products derived from this  
  16. 16.  * software without specific prior written permission.  
  17. 17.  *  
  18. 18.  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"  
  19. 19.  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE  
  20. 20.  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE  
  21. 21.  * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,  
  22. 22.  * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,  
  23. 23.  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,  
  24. 24.  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;  
  25. 25.  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND  
  26. 26.  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT  
  27. 27.  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS  
  28. 28.  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.  
  29. 29.  */   

ruby 代码
 
  1. package org.hsqldb.sample;  
  2.   
  3. import java.sql.Connection;  
  4. import java.sql.DriverManager;  
  5. import java.sql.ResultSet;  
  6. import java.sql.ResultSetMetaData;  
  7. import java.sql.SQLException;  
  8. import java.sql.Statement;  
  9.   
  10. /**  
  11.  * Title:        Testdb  
  12.  * Description:  simple hello world db example of a  
  13.  *               standalone persistent db application  
  14.  *  
  15.  *               every time it runs it adds four more rows to sample_table  
  16.  *               it does a query and prints the results to standard out  
  17.  *  
  18.  * Author: Karl Meissner karl@meissnersd.com  
  19.  */  
  20. public class Testdb {  
  21.   
  22.     Connection conn;                                                //our connnection to the db - presist for life of program  
  23.   
  24.     // we dont want this garbage collected until we are done  
  25.     public Testdb(String db_file_name_prefix) throws Exception {    // note more general exception  
  26.   
  27.         // Load the HSQL Database Engine JDBC driver  
  28.         // hsqldb.jar should be in the class path or made part of the current jar  
  29.         Class.forName("org.hsqldb.jdbcDriver");  
  30.   
  31.         // connect to the database.   This will load the db files and start the  
  32.         // database if it is not alread running.  
  33.         // db_file_name_prefix is used to open or create files that hold the state  
  34.         // of the db.  
  35.         // It can contain directory names relative to the  
  36.         // current working directory  
  37.         conn = DriverManager.getConnection("jdbc:hsqldb:"  
  38.                                            + db_file_name_prefix,    // filenames  
  39.                                            "sa",                     // username  
  40.                                            "");                      // password  
  41.     }  
  42.   
  43.     public void shutdown() throws SQLException {  
  44.   
  45.         Statement st = conn.createStatement();  
  46.   
  47.         // db writes out to files and performs clean shuts down  
  48.         // otherwise there will be an unclean shutdown  
  49.         // when program ends  
  50.         st.execute("SHUTDOWN");  
  51.         conn.close();    // if there are no other open connection  
  52.     }  
  53.   
  54. //use for SQL command SELECT  
  55.     public synchronized void query(String expression) throws SQLException {  
  56.   
  57.         Statement st = null;  
  58.         ResultSet rs = null;  
  59.   
  60.         st = conn.createStatement();         // statement objects can be reused with  
  61.   
  62.         // repeated calls to execute but we  
  63.         // choose to make a new one each time  
  64.         rs = st.executeQuery(expression);    // run the query  
  65.   
  66.         // do something with the result set.  
  67.         dump(rs);  
  68.         st.close();    // NOTE!! if you close a statement the associated ResultSet is  
  69.   
  70.         // closed too  
  71.         // so you should copy the contents to some other object.  
  72.         // the result set is invalidated also  if you recycle an Statement  
  73.         // and try to execute some other query before the result set has been  
  74.         // completely examined.  
  75.     }  
  76.   
  77. //use for SQL commands CREATE, DROP, INSERT and UPDATE  
  78.     public synchronized void update(String expression) throws SQLException {  
  79.   
  80.         Statement st = null;  
  81.   
  82.         st = conn.createStatement();    // statements  
  83.   
  84.         int i = st.executeUpdate(expression);    // run the query  
  85.   
  86.         if (i == -1) {  
  87.             System.out.println("db error : " + expression);  
  88.         }  
  89.   
  90.         st.close();  
  91.     }    // void update()  
  92.   
  93.     public static void dump(ResultSet rs) throws SQLException {  
  94.   
  95.         // the order of the rows in a cursor  
  96.         // are implementation dependent unless you use the SQL ORDER statement  
  97.         ResultSetMetaData meta   = rs.getMetaData();  
  98.         int               colmax = meta.getColumnCount();  
  99.         int               i;  
  100.         Object            o = null;  
  101.   
  102.         // the result set is a cursor into the data.  You can only  
  103.         // point to one row at a time  
  104.         // assume we are pointing to BEFORE the first row  
  105.         // rs.next() points to next row and returns true  
  106.         // or false if there is no next row, which breaks the loop  
  107.         for (; rs.next(); ) {  
  108.             for (i = 0; i < colmax; ++i) {  
  109.                 o = rs.getObject(i + 1);    // Is SQL the first column is indexed  
  110.   
  111.                 // with 1 not 0  
  112.                 System.out.print(o.toString() + " ");  
  113.             }  
  114.   
  115.             System.out.println(" ");  
  116.         }  
  117.     }                                       //void dump( ResultSet rs )  
  118.   
  119.     public static void main(String[] args) {  
  120.   
  121.         Testdb db = null;  
  122.   
  123.         try {  
  124.             db = new Testdb("db_file");  
  125.         } catch (Exception ex1) {  
  126.             ex1.printStackTrace();    // could not start db  
  127.   
  128.             return;                   // bye bye  
  129.         }  
  130.   
  131.         try {  
  132.   
  133.             //make an empty table  
  134.             //  
  135.             // by declaring the id column IDENTITY, the db will automatically  
  136.             // generate unique values for new rows- useful for row keys  
  137.             db.update(  
  138.                 "CREATE TABLE sample_table ( id INTEGER IDENTITY, str_col VARCHAR(256), num_col INTEGER)");  
  139.         } catch (SQLException ex2) {  
  140.   
  141.             //ignore  
  142.             //ex2.printStackTrace();  // second time we run program  
  143.             //  should throw execption since table  
  144.             // already there  
  145.             //  
  146.             // this will have no effect on the db  
  147.         }  
  148.   
  149.         try {  
  150.   
  151.             // add some rows - will create duplicates if run more then once  
  152.             // the id column is automatically generated  
  153.             db.update(  
  154.                 "INSERT INTO sample_table(str_col,num_col) VALUES('Ford', 100)");  
  155.             db.update(  
  156.                 "INSERT INTO sample_table(str_col,num_col) VALUES('Toyota', 200)");  
  157.             db.update(  
  158.                 "INSERT INTO sample_table(str_col,num_col) VALUES('Honda', 300)");  
  159.             db.update(  
  160.                 "INSERT INTO sample_table(str_col,num_col) VALUES('GM', 400)");  
  161.   
  162.             // do a query  
  163.             db.query("SELECT * FROM sample_table WHERE num_col &lt 250");  
  164.   
  165.             // at end of program  
  166.             db.shutdown();  
  167.         } catch (SQLException ex3) {  
  168.             ex3.printStackTrace();  
  169.         }  
  170.     }    // main()  
  171. }    // class Testdb  
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics