シェルスクリプトを使って、SQLiteのレコードを取得する

表題のとおり。

ただ取得するだけならこんなカンジかと。

#!/bin/sh
SQL="SELECT * FROM table_name"
COMMAND="sqlite database_name"
echo $SQL | $COMMAND
exit 0

今回はその後ローカルであれこれしたい(だろう)から、最終的にCSVにしたい。
文字コードはローカルで変換してもらうとして(?)、その直前まではやってあげたい。


SQLiteのデリミタって「|」なんだよね。
それを「,」に変えたい。

「.help」で確認する。

sqlite> .help
.databases             List names and files of attached databases
.dump ?TABLE? ...      Dump the database in a text format
.echo ON|OFF           Turn command echo on or off
.exit                  Exit this program
.explain ON|OFF        Turn output mode suitable for EXPLAIN on or off.
.header(s) ON|OFF      Turn display of headers on or off
.help                  Show this message
.indices TABLE         Show names of all indices on TABLE
.mode MODE             Set mode to one of "line(s)", "column(s)",
                       "insert", "list", or "html"
.mode insert TABLE     Generate SQL insert statements for TABLE
.nullvalue STRING      Print STRING instead of nothing for NULL data
.output FILENAME       Send output to FILENAME
.output stdout         Send output to the screen
.prompt MAIN CONTINUE  Replace the standard prompts
.quit                  Exit this program
.read FILENAME         Execute SQL in FILENAME
.schema ?TABLE?        Show the CREATE statements
.separator STRING      Change separator string for "list" mode
.show                  Show the current values for various settings
.tables ?PATTERN?      List names of tables matching a pattern
.timeout MS            Try opening locked tables for MS milliseconds
.width NUM NUM ...     Set column widths for "column" mode
sqlite>

とあるので、試してみる…

sqlite> .separator ,
sqlite> select id, name from test;
1,test1
2,test2
sqlite>


で、これをどうシェルスクリプトに組み込むかってことなんだけど…
さすがにechoで出力してるんで、順次コマンドを送るのはムリっぽい。
かといってSELECTの前にドット付きのコマンドを送れるワケもない。


そこで、sqliteそのもののヘルプを確認する。

sqlite -help
Usage: sqlite [OPTIONS] FILENAME [SQL]
Options are:
   -init filename       read/process named file
   -echo                print commands before execution
   -[no]header          turn headers on or off
   -column              set output mode to 'column'
   -html                set output mode to HTML
   -line                set output mode to 'line'
   -list                set output mode to 'list'
   -separator 'x'       set output field separator (|)
   -nullvalue 'text'    set text string for NULL values
   -version             show SQLite version
   -help                show this text, also show dot-commands


オプションをつければいいか。

sqlite -separator ',' database_name


ところが…

1','test1
2','test2


おいおい。

sqlite -separator , database_name

ってことね。


あと、格納されている値の一部に改行(\n)が入ってる。そこはCSVでちゃんと認識させたいから、その項目だけは「"」でくくってやる必要がある。
で、どうやって文字列を連結できるのかと…

メモ。sqliteでconcat、つまり文字列の結合をやりたい時は、"||"をつかう。

sqliteで文字列結合 - もぎゃろぐ

このblogの人も書いてるけど、

なんでそんな変な記号を選んだかなぁ...

sqliteで文字列結合 - もぎゃろぐ

には同意せざるを得ない。


ってことはこうなるか。

SQL="SELECT id, name, '\"'||note||'\"' FROM table_name;"


エスケープし忘れて、怒られたのはナイショだ。


あとは

   -[no]header          turn headers on or off

でヘッダが出力されるので、

sqlite -separator , -header database_name

と修正しておしまい。


その2へつづく…