天天看點

SQLite:Java操作SQLite 1.SQLiteJDBC 2. Java 代碼

1.SQLiteJDBC

SQLite JDBC Driver 可以在這個網站下載下傳https://bitbucket.org/xerial/sqlite-jdbc/overview,目前穩定版本sqlite-jdbc-3.7.2.jar

2. Java 代碼

添加sqlite-jdbc-3.7.2.jar,與你添加其他jar包的方法一樣。

[java]  view plain copy

  1. import java.sql.Connection;  
  2. import java.sql.DriverManager;  
  3. import java.sql.ResultSet;  
  4. import java.sql.SQLException;  
  5. import java.sql.Statement;  
  6. public class SQLiteTest  
  7. {  
  8.   public static void main(String[] args) throws ClassNotFoundException  
  9.   {  
  10.     // load the sqlite-JDBC driver using the current class loader  
  11.     Class.forName("org.sqlite.JDBC");  
  12.     Connection connection = null;  
  13.     try  
  14.     {  
  15.       // create a database connection  
  16.       connection = DriverManager.getConnection("jdbc:sqlite:sample.db");  
  17.       Statement statement = connection.createStatement();  
  18.       statement.setQueryTimeout(30);  // set timeout to 30 sec.  
  19.       statement.executeUpdate("drop table if exists person");  
  20.       statement.executeUpdate("create table person (id integer, name string)");  
  21.       statement.executeUpdate("insert into person values(1, 'leo')");  
  22.       statement.executeUpdate("insert into person values(2, 'yui')");  
  23.       ResultSet rs = statement.executeQuery("select * from person");  
  24.       while(rs.next())  
  25.       {  
  26.         // read the result set  
  27.         System.out.println("name = " + rs.getString("name"));  
  28.         System.out.println("id = " + rs.getInt("id"));  
  29.       }  
  30.     }  
  31.     catch(SQLException e)  
  32.     {  
  33.       // if the error message is "out of memory",   
  34.       // it probably means no database file is found  
  35.       System.err.println(e.getMessage());  
  36.     }  
  37.     finally  
  38.     {  
  39.       try  
  40.       {  
  41.         if(connection != null)  
  42.           connection.close();  
  43.       }  
  44.       catch(SQLException e)  
  45.       {  
  46.         // connection close failed.  
  47.         System.err.println(e);  
  48.       }  
  49.     }  
  50.   }  
  51. }  

參考資料:https://bitbucket.org/xerial/sqlite-jdbc/overview

繼續閱讀