2022/8/17 您所在的位置:网站首页 c语言导出txt数据 2022/8/17

2022/8/17

2024-01-06 13:28| 来源: 网络整理| 查看: 265

使用的数据库为sqlite3

使用的sqlite3自带的函数为

函数名功能

sqlite3_open

打开数据库,如果数据库不存在,则创建并打开

sqlite3_errmsg

打印错误码对应的错误信息

sqlite3_errcode

sqlite3_close

sqlite3_exec

指定一条sql语句

其中,使用sqlite3_exec函数完成在c语言代码中运行sqlite语句,从而实现数据的快速导入

函数原型: int sqlite3_exec(       sqlite3* db,                               /* An open database */       const char *sql,                           /* SQL to be evaluated */       int (*callback)(void*,int,char**,char**),  /* Callback function */       void *arg,                                 /* 1st argument to callback */       char **errmsg                              /* Error msg written here */     );

参数:     sqlite3* db:打开的数据库;     char *sql:要被执行的sql语句;     int (*callback)(void*,int,char**,char**):函数指针,该指针指向返回值为int类型,参数列表为void*,int,char**,char**的函数;                                             只有在sql语句是查询语句的时候有用,其余时候填NULL;     void *arg:会被传递给回调函数的第一个参数;     char **errmsg:该二级指针指向的一级指针会指向错误信息;

基本思路为:一行一行的读取文件内容,利用单词与注释之间的多个空格将两者分割存放在不同的数组中,最后使用sprintf函数拼接成sql语句并使用sqlite3_exec函数存入数据库中。

代码实现:

#include #include #include #include #include #include #include #include //打印错误信息的宏函数 #define ERR_MSG(msg) do{\ fprintf(stderr,"__%d__",__LINE__);\ perror(msg);\ }while(0) int main(int argc, const char *argv[]) { //打开数据库 sqlite3* db = NULL; if(sqlite3_open("./dict.db",&db) != SQLITE_OK) { printf("err_code:%d\n",sqlite3_errcode(db)); printf("errmsg:%s\n",sqlite3_errmsg(db)); fprintf(stderr,"__%d__ sqlite3_open failed\n",__LINE__); return -1; } printf("sqlite3_open success\n"); //创建一个表格 char* sql = "create table if not exists dir(word char, mean char);" ; char* errmsg = NULL; if(sqlite3_exec(db, sql, NULL, NULL, &errmsg) != SQLITE_OK) { fprintf(stderr, "__%d__ sqlite3_exec:%s\n", __LINE__, errmsg); return -1; } printf("create table success\n"); //以只读方式打开原文件 int fd = open("./dict.txt",O_RDONLY); if(fd


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有