SQLite3をC言語で使う練習。
ちょうどよい記事を見つけてしまったので練習してみる。
元祖 サトシのブログ:「SQLite の INSERT は遅いのか?」
簡潔なテストコード。ちょっと拝借してSQLite3用に手直し。環境は、
適当なフォルダに以下のファイルを作成。
instest.c
#include <stdio.h> #include <stdlib.h> #include <sqlite3.h> #define INSERT_COUNT 1000 int main(int argc, char *argv[]) { sqlite3 *db; char *errmsg; int i; /* SQLite データベースを OPEN */ sqlite3_open("instest.db", &db); if (!db) { printf("%s: %s\n", argv[0], errmsg); exit(-1); } /* BEGIN TRANSACTION */ #ifdef USE_TRANSACTION (void)sqlite3_exec(db, "BEGIN", NULL, NULL, &errmsg); #endif /* INSERT */ for (i = 0; i < INSERT_COUNT; i++) { char *sql; sql = sqlite3_mprintf("INSERT INTO test VALUES (%d)", i); (void)sqlite3_exec(db, sql, NULL, NULL, &errmsg); } /* COMMIT TRANSACTION */ #ifdef USE_TRANSACTION (void)sqlite3_exec(db, "COMMIT", NULL, NULL, &errmsg); #endif sqlite3_close(db); }
そしてビルド。
$ gcc -lsqlite3 -o instest instest.c
DBファイルを作成。
$ sqlite3 instest.db SQLite version 3.x.x Enter ".help" for instructions sqlite> create table test ( id integer ); sqlite> .q
実行。
$ ./instest
ガリガリガリガリ・・・・・・・・・・・・・・
終わらないのでCtrl+C。トランザクションを有効にしてビルド。
$ gcc -DUSE_TRANSACTION -lsqlite3 -o instest instest.c
もっかい実行。
$ ./instest
一瞬で終了。こんな感じで作れるみたい。