2008年7月10日木曜日

【SQLite】 SQLiteをVCから使う

本家から以下をダウンロード。
sqlite-source-3_5_9.zip
sqlitedll-3_5_9.zip
同じフォルダーに展開して、VCのlib.exeコマンドでsqlite3.libを作る。

lib.exeはC:\Program Files\Microsoft Visual Studio 8\VC\bin\lib.exeにある。
また、mspdb80.dllでエラーが出る場合は、C:\Program Files\Microsoft Visual Studio 8\Common7\IDEからコピーしておく。

C:\sqlite-3_5_9> lib.exe /def:sqlite3.def

sqlite3.libが出来ていることを確認する。

VCでsqlite3.hをインクルードに、sqlite3.libをライブラリに加える。
リンカの入力にある追加の依存ファイルにも追加することを忘れない。
これでVCで使うための準備完了。

SELECTを実行するサンプルプログラム。
まず、データをコマンドから入力しておく。

# sqlite3 test.db
sqlite> create table test (id integer primary key, title char(256), desc text);
sqlite> insert into marker values('1', 'Test01', 'This is a test!');
sqlite> select * from test;
sqlite> .header on
sqlite> .mode column
sqlite> select * from test;
sqlite> .help
sqlite> .schema
sqlite> .table
sqlite> .q


C言語のコード


#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include "sqlite3.h"

using namespace std;

int main(int argc, char** argv)
{
sqlite3* db;
int err;
char* db_name = (argc > 1) ? argv[1] : "test.db";

// open database
err = sqlite3_open(db_name, &db);

if (err != SQLITE_OK) {
// show error and exit.
fputs(sqlite3_errmsg(db), stderr);
exit(1);
}

// select
sqlite3_stmt* select_sql;
char *sql = "select * from test;";

err = sqlite3_prepare(db, sql, strlen(sql), &select_sql, NULL);

while ((err = sqlite3_step(select_sql)) == SQLITE_ROW) {
int id = sqlite3_column_int(select_sql, 0);
const unsigned char *title = sqlite3_column_text(select_sql, 1);
const unsigned char *desc = sqlite3_column_text(select_sql, 2);
cout << title << endl;
cout << desc << endl;
}

sqlite3_finalize(select_sql);

// close database
err = sqlite3_close(db);

return EXIT_SUCCESS;
}




今回のエントリーはこちらを参考にしました。

ラベル: , ,

0 件のコメント:

コメントを投稿

登録 コメントの投稿 [Atom]

この投稿へのリンク:

リンクを作成

<< ホーム