【Java】 SQLite を Java で利用する

前提条件

 以下の関連記事を参考に、SQLiteとサンプルテーブルを作成しておく
http://blogs.yahoo.co.jp/dk521123/33027330.html

設定

 [1] 以下のサイトから、JDBCドライバーをダウンロードする
   (例えば、「sqlite-jdbc-3.7.2.jar」)
https://bitbucket.org/xerial/sqlite-jdbc
 [2] Eclipse で、新規プロジェクトを作成
 [3] 新規プロジェクトのあるフォルダに、任意のフォルダ(例えば「lib」)を作成し
     その配下に、JDBCドライバーのJarファイルを置く
    (【新規プロジェクトのあるフォルダ】\lib\sqlite-jdbc-3.7.2.jar)
 [4] そのプロジェクトを右クリックし、[Properties]-[Java Build Path]-[Libraries]-[Add JARs]を選択し
     手順[3]のJARファイルを追加する

サンプル

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class SampleSqlLite {

   public static void main(String[] args) throws ClassNotFoundException {
      Class.forName("org.sqlite.JDBC");

      Connection connection = null;
      try {
         connection = DriverManager.getConnection("jdbc:sqlite:C:\\pg\\sqlite\\sample.sqlite3");
         Statement statement = connection.createStatement();
         statement.setQueryTimeout(30); // set timeout to 30 sec.

         ResultSet results = statement.executeQuery("select * from Person");
         while (results.next()) {
            System.out.println("name = " + results.getString("name"));
            System.out.println("id = " + results.getInt("id"));
         }
      } catch (SQLException e) {
         System.err.println(e.getMessage());
      } finally {
         try {
            if (connection != null) {
               connection.close();
            }
         } catch (SQLException e) {
            System.err.println(e);
         }
      }
   }
}