てけとーぶろぐ。

ソフトウェアの開発と、お絵かきと、雑記と。

SQLiteのDBにJDBCで接続してSQLを実行する

本当はOracleのDBでやりたいのだけど、すぐ試したかったのでSQLiteを使いました。

驚くほどお手軽だったので、ちょっとSQLを触ってみたいという人はSQLiteを使えばいいと思いました。

sqlite-shellでテーブルの準備

コマンドラインSQLiteのDBを操作できるsqlite-shellを使ってテーブルの準備をします。

SQLite Download Pageより「Precompiled Binaries for Windows」にある「sqlite-shell-win32-x86-3080704.zip」をダウンロードしました。

「C:\temp」に入れてCommand Line Shell For SQLiteを参考にコマンドプロンプトから以下のように入力するともうテーブルができてしまう。

>cd c:\temp
>sqlite3.exe test.db
SQLite version 3.8.7.4 2014-12-09 01:34:36
Enter ".help" for usage hints.
sqlite> create table tbl1(one varchar(10), two smallint);
sqlite> insert into tbl1 values('hello!',10);
sqlite> insert into tbl1 values('goodbye', 20);
sqlite> select * from tbl1;
hello!|10
goodbye|20

SQLiteJDBCドライバの使用

SQLite JDBC Driverから「sqlite-jdbc-3.8.7.jar」をダウンロード。
これも「C:\temp」に入れてしまう。

SQLiteJDBCドライバを使うプログラムを「C:\temp\Sample.java」として作成。

内容は以下の通り。

import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;

public class Sample {
    public static void main(String[] args) throws ClassNotFoundException {

        String sql = "";
        try {
            File file = new File("Sample.sql");
            BufferedReader br = new BufferedReader(new FileReader(file));

            String str;
            while ((str = br.readLine()) != null) {
                sql = sql + str + System.getProperty("line.separator");
            }
            br.close();
        } catch (FileNotFoundException e) {
            System.out.println(e);
        } catch (IOException e) {
            System.out.println(e);
        }

        Class.forName("org.sqlite.JDBC");
        Connection connection = null;
        Statement statement = null;
        try {
            connection = DriverManager
                    .getConnection("jdbc:sqlite:C:/temp/test.db");
            statement = connection.createStatement();
            statement.setQueryTimeout(30);

            ResultSet rs = statement.executeQuery(sql);
            ResultSetMetaData rsmd = rs.getMetaData();
            while (rs.next()) {
                for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                    System.out.print(rs.getString(i));
                    System.out.print(i < rsmd.getColumnCount() ? "," : "");
                }
                System.out.print(System.getProperty("line.separator"));
            }
        } catch (SQLException e) {
            System.err.println(e.getMessage());
        } finally {
            try {
                if (statement != null) {
                    statement.close();
                }
            } catch (SQLException e) {
                System.err.println(e);
            }
            try {
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                System.err.println(e);
            }
        }
    }
}

先ほど作成したDBに接続し「Sample.sql」というファイルから読み込んだSQLを実行するという内容です。

ですので「C:\temp\Sample.sql」も作成します。

内容は以下の通り。

SELECT * FROM tbl1

プログラムのコンパイルと実行

JDKはインストール済みで、java.exeやjavac.exeにパスも通っている前提で、コマンドプロンプトからプログラムのコンパイルと実行をします。

>cd c:\temp
>javac.exe Sample.java
>java.exe -classpath ".;sqlite-jdbc-3.8.7.jar" Sample

すると、コマンドプロンプトに、SQLの実行結果が表示されます。

あらお手軽。