tSeiya's blog

行動結果のアウトプット場

Javaで「タブで区切られたデータ」をsqliteのテーブルへ書き込む

概要

タブで区切られた以下のリンク先にあるようなデータセットSQLiteのテーブルへ書き込むJavaプログラムです.

統計を学びたい人へ贈る、統計解析に使えるデータセットまとめ http://d.hatena.ne.jp/hoxo_m/20120214/p1 - ほくそ笑む

今回は例と「ニューヨークの大気状態観測値:http://www.is.titech.ac.jp/~mase/mase/html.jp/temp/airquality.jp.html」である【airquality】を使います.

データセット

左から順にID,Ozone, Solar, ...と並んで,タブ区切りになっています.
以下,一部データを抜粋しました.

	Ozone	Solar.R	Wind	Temp	Month	Day
1	41	190	7.4	67	5	1
2	36	118	8	72	5	2

プログラム

今回は,サクッと作りたかったので,以下の記事に書かれているものはほぼ参考にしました.

[SQLite JDBC] Javaで始めるSQLiteデータベース入門 http://leoclock.blogspot.jp/2008/10/sqlitejdbc-javasqlite.html - Leo's Chronicle

http://www.xerial.org/maven/repository/artifact/org/xerial/sqlite-jdbc/にある【sqlite-jdbc-3.7.2.jar】とhttp://www.zentus.com/sqlitejdbc/にある【sqlitejdbc-v056.jar】をダウンロードしてきて,classesと名付けたディレクトリにまとめておきます.

大まかな流れ

  1. データベースに繋ぐ
  2. 既に,airqualityテーブルがあれば削除する
  3. airqualityテーブルを作成する
  4. airquality.txt からデータを一行ずつ読み込む
  5. データをタブ毎にトークンで区切って,カンマで繋げ,SQL文として体裁を整える
  6. SQL文を実行する(airqualityテーブルへ挿入する)
  7. 結果を表示する
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.*;
import java.io.*;


public class Txt2Sqlite
{
 public static void main(String[] args) throws ClassNotFoundException
 {
   // load the sqlite-JDBC driver using the current class loader
   Class.forName("org.sqlite.JDBC");
  
   Connection connection = null;
   try
   {
     // create a database connection
     connection = DriverManager.getConnection("jdbc:sqlite:sample.db");
     Statement statement = connection.createStatement();
     statement.setQueryTimeout(30);  // set timeout to 30 sec.
    
     statement.executeUpdate("drop table if exists airquality");
     statement.executeUpdate("create table airquality (id integer, Ozone string, Solar string, Wind double, Temp double, Month integer, day integer)");

     try {
        File data = new File("airquality.txt"); //sqliteのデータベースに格納予定のデータセット
        BufferedReader br = new BufferedReader(new FileReader(data));
        String line = ""; //一行ずつ読み込む
        String insert = ""; //insertする文
        boolean header = true; //ヘッダーフラグ
        while((line = br.readLine()) != null)
        {
          StringTokenizer token = new StringTokenizer(line, "\t");
          while(token.hasMoreTokens())
          {
            insert += "\'"+token.nextToken() + "\', ";
          }
          if(header) //ヘッダーはinsertしない
          { 
            header = false; 
          }
          else
          {        
            insert = insert.substring(0,insert.length()-2);//最後の","までを削除した文
            insert ="insert into airquality values("+insert+")";        
            //System.out.println(insert);
            statement.executeUpdate(insert);
          }
          insert = "";//中身をカラにする          
        }
     } 
     catch (FileNotFoundException e)
     {
      e.printStackTrace();
     }
     catch (IOException e)
     {
      e.printStackTrace();
     }

     ResultSet rs = statement.executeQuery("select * from airquality");
     while(rs.next())
     {
       // read the result set
       System.out.println(rs.getString("Ozone")+"\t"+rs.getString("Solar")+"\t"+rs.getString("Wind")+"\t"+rs.getString("Temp")+"\t"+rs.getString("Month")+"\t"+rs.getString("Day"));
     }
   }
   catch(SQLException e)
   {
     // if the error message is "out of memory",
     // it probably means no database file is found
     System.err.println(e.getMessage());
   }
   finally
   {
     try
     {
       if(connection != null)
         connection.close();
     }
     catch(SQLException e)
     {
       // connection close failed.
       System.err.println(e);
     }
   }
 }
}

↑プログラム,↓コンパイル&実行

javac -cp .:./classes/* Txt2Sqlite.java
java -cp .:./classes/* Txt2Sqlite