微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

[代码实例][C语言][sqlite3]用SQL语句查询数据库的实例

下载sqlite3代码

https://www.sqlite.org/

编译安装sqlite3的Makefile

INSTALL_PATH    =/usr/local

all: install

libsqlite3.so: sqlite3.c sqlite3.h
    gcc -shared -fPIC $< -o $@

install_lib: libsqlite3.so install_headers
    cp libsqlite3.so $(INSTALL_PATH)/lib
    ldconfig $(INSTALL_PATH)/lib

install_headers: sqlite3.h sqlite3ext.h
    cp $^ $(INSTALL_PATH)/include/

sqlite3: install_lib shell.c
    $(CC) shell.c -o $@ -lsqlite3 -lpthread -ldl

install_shell: sqlite3
    cp $^ $(INSTALL_PATH)/bin

install: install_lib install_shell

uninstall:
    rm -f \
        $(INSTALL_PATH)/lib/libsqlite3.so \
        $(INSTALL_PATH)/include/sqlite3.h \
        $(INSTALL_PATH)/include/sqlite3ext.h \
        $(INSTALL_PATH)/bin/sqlite3

clean:
    rm -f *.so sqlite3

.PHONY: install install_lib install_headers install_shell clean

客户端程序

/* * main.c */
#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h>

static int callback(void * not_used,int argc,char * argv[],char * col_names[]);

int main(int argc,char * argv[])
{
    sqlite3 * db = NULL;
    char * zErrMsg = NULL;

    if(argc != 3)
    {
        fprintf(stderr,"Usage: %s DATABASE sql-STATEMENT\n",argv[0]);
        return EXIT_FAILURE;
    }

    if(sqlite3_open(argv[1],&db) != sqlITE_OK)
    {
        fprintf(stderr,"Can't open database: %s\n",sqlite3_errmsg(db));
        sqlite3_close(db);
        return EXIT_FAILURE;
    }

    if(sqlite3_exec(db,argv[2],callback,NULL,&zErrMsg) != sqlITE_OK)
    {
        fprintf(stderr,"sql error: %s\n",zErrMsg);
        sqlite3_free(zErrMsg);
    }

    sqlite3_close(db);

    return EXIT_SUCCESS;
}

static int callback(void * not_used,char * col_names[])
{
    for(int i; i < argc; i++)
        printf("%s = %s\n",col_names[i],argv[i] ? argv[i] : "NULL");
    printf("\n");
    return 0;
}

编译客户端程序的Makefile

all: main

main: main.c gcc main.c -o main -lsqlite3 -lpthread -ldl clean: rm -r main .PHONY: clean

数据库脚本文件

/* * test.sql */

DROP TABLE main.user;
CREATE TABLE main.user( Name TEXT,Age INTEGER );

INSERT INTO user VALUES('Huo Yun',27);
INSERT INTO user VALUES('Gao Jingzhuo',30);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐