JAVA中的sqlite

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