sqlit使用

sqlit使用

sqlite3* db;
int db_init() {
    if(SQLITE_OK != sqlite3_open("test.db", &db))
        return 0;
    sqlite3_exec(db, "create table if not exists alluser(username TEXT PRIMARY KEY, password TEXT NOT NULL)",
        NULL, NULL, NULL);
    sqlite3_exec(db, "create table if not exists contacts(username TEXT, contact TEXT)",
        NULL, NULL, NULL);
    sqlite3_exec(db, "create table if not exists grouplist(groupID INTEGER PRIMARY KEY autoincrement NOT NULL, creator TEXT)",
        NULL, NULL, NULL);
    sqlite3_exec(db, "create table if not exists groupmember(groupID INTEGER NOT NULL, member TEXT NOT NULL)",
        NULL, NULL, NULL);
    sqlite3_exec(db, "create table if not exists offlinemsg(sendto TEXT NOT NULL, msg TEXT NOT NULL)",
        NULL, NULL, NULL);
    printf("db init successful!\n");
    return 1;
}

这是打开数据库并且运行sql语句的一段代码

编译时候用的makefile文件:

src = dbtest.c ./util/util.c ./util/cJSON.c ./util/sqlite3.c
server : $(src)
    gcc -o dbtest $(src) -lpthread -lm -ldl -w `pkg-config --cflags --libs gtk+-2.0`

下面是select一个系列元组的代码

#include "util/util.h"
#include

sqlite3* db;
int db_init() {
    if(SQLITE_OK != sqlite3_open("test.db", &db))
        return 0;
    sqlite3_exec(db, "create table if not exists alluser(username TEXT PRIMARY KEY, password TEXT NOT NULL)",
        NULL, NULL, NULL);
    sqlite3_exec(db, "create table if not exists contacts(username TEXT, contact TEXT)",
        NULL, NULL, NULL);
    sqlite3_exec(db, "create table if not exists grouplist(groupID INTEGER PRIMARY KEY autoincrement NOT NULL, creator TEXT)",
        NULL, NULL, NULL);
    sqlite3_exec(db, "create table if not exists groupmember(groupID INTEGER NOT NULL, member TEXT NOT NULL)",
        NULL, NULL, NULL);
    sqlite3_exec(db, "create table if not exists offlinemsg(sendto TEXT NOT NULL, msg TEXT NOT NULL)",
        NULL, NULL, NULL);
    printf("db init successful!\n");
    return 1;
}

void get_table_test() {
    sqlite3_exec(db, "insert into alluser values(\'abc\',\'def\')",NULL, NULL, NULL);
    sqlite3_exec(db, "insert into alluser values(\'abc2\',\'def\')",NULL, NULL, NULL);
    ///sqlite3_exec(db, "select username,password from alluser where password = \'def\'",NULL, res, NULL);
    char **res; char *errmsg; int nrow; int ncol;
    sqlite3_get_table(db, "select username,password from alluser where password = \'def\'", &res, &nrow, &ncol, &errmsg);
    int i, j; int nindex = ncol;
   //前ncol个res字符串代表属性名称,后面nrow*ncol个数据,代表select的结果
    for(i=0;ifor(j=0;jprintf("%s\n", res[nindex]);
            nindex++;
        }
        //printf("\n");
    }
    printf("get table test success\n");
}

int main() {
    db_init();
    get_table_test();
}

你可能感兴趣的:(sqlit)