LoginSignup
20
18

More than 5 years have passed since last update.

C言語でSQLiteを使う

Last updated at Posted at 2015-01-19

概要

SQLiteのCドライバを使って
SQLiteにアクセスするサンプルを作りましたので、そのソースと手順などを共有したいと思います。

環境構築

CentOSを想定してます。

yum install -y update
yum install -y vim gcc sqlite sqlite-devel

データベースの設定

テスト用のデータを入力します。

sqlite3 db_test.sqlite3                       # データベースファイル作成
create table tb_test(id integer,name text);   # テーブル作成
# testデータ投入
insert into tb_test(id,name) values(1,'aaa');
insert into tb_test(id,name) values(2,'bbb');
insert into tb_test(id,name) values(3,'ccc');
.quit                                         # 終了 

SQLiteにアクセス

詳細な指定をしたい場合、sqlite3_open()よりもsqlite3_open_v2()、
sqlite3_exec()よりもsqlite3_open_v2()を使った方が良いです。

sqlite.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sqlite3.h>
int print_resp( void * , int , char ** , char ** );

int main( void ){
  int ret       = 0;
  sqlite3 *conn = NULL;
  char *err_msg = NULL;
  char sql_str[255];
  memset( &sql_str[0] , 0x00 , sizeof(sql_str) );

  // アクセス
  ret = sqlite3_open(
          "./db_test.sqlite3" , // DBファイル名
          &conn                 // DBコネクション
        );
  if( SQLITE_OK != ret ){
    // error
    exit(-1);
  }

  // SQL文発行
  snprintf( &sql_str[0] , sizeof(sql_str)-1 , "select * from tb_test" );
  ret = sqlite3_exec(
          conn        , // DBコネクション
          &sql_str[0] , // SQL文
          print_resp  , // コールバック関数
          NULL        , // CB関数に渡す引数
          &err_msg      // エラーメッセージ
        );
  if( SQLITE_OK != ret ){
    // error
    sqlite3_close( conn );
    sqlite3_free( err_msg );
    exit(-1);
  }

  // 後片づけ
  ret = sqlite3_close( conn );
  if( SQLITE_OK != ret ){
    // error
    exit(-1);
  }  
  return 0;
}

int print_resp(
      void *get_prm   , // sqlite3_exec()の第4引数
      int col_cnt     , // 列数
      char **row_txt  , // 行内容
      char **col_name   // 列名
    ){
  printf( "%s : %s\n" , row_txt[0] , row_txt[1] );
  return 0;
}

コンパイル、実行

-Lはlibsqlite3.soの場所を、-Iはsqlite3.hが配置されているディレクトリを指定します。

gcc -Wall -o sqlite sqlite.c -lsqlite3 -L/usr/lib64/ -I/usr/include/
./sqlite
1 : aaa
2 : bbb
3 : ccc
20
18
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
20
18