C语言调用sqlite3命令语句实现将txt文件导入到数据库中
。。
·
txt文档格式不标准,无需分为三列,仅分为两列即可
#include <stdio.h>
#include <string.h>
#include <sqlite3.h>
#include <stdlib.h>
int main(int argc, const char *argv[])
{
//读取txt文件到数据库
FILE* fp = fopen("./dict.txt", "r"); //只读方式打开txt文件
if(NULL == fp)
{
perror("fopen");
return -1;
}
//创建并打开数据库
sqlite3* db = NULL;
if(sqlite3_open("./dict.db", &db) != SQLITE_OK)
{
fprintf(stderr, "__%d__ sqlite3_open : %d | %s\n", __LINE__, sqlite3_errcode(db), sqlite3_errmsg(db));
return -1;
}
printf("sqlite3_open sucess __%d__\n", __LINE__);
//创建表格,[数据库中代码怎么写,此处就怎么写]
char sql[128] = "create table if not exists dictionary (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("table dictionary create sucess __%d__ \n", __LINE__);
//读取txt文件中的字符串
char buf[128] = "";
char buf_word[32] = ""; //英文单词
char buf_prop[32] = ""; //词性
char buf_mean[32] = ""; //单词释义
char* p_temp = NULL;
while(1)
{
bzero(buf, sizeof(buf));
bzero(buf_word, sizeof(buf_mean));
bzero(buf_mean, sizeof(buf_mean));
if(fgets(buf, sizeof(buf), fp) == NULL) //遇到换行会停止读取,并自动补\0
{
break; //读取结束,fgets返回值为NULL
}
//写入到数据库中
p_temp = buf;
int i = 0;
int j = 0;
//printf("%s\n", buf);
//sleep(1);
//将读取到的一整串字符串分开
while(1)
{
if(*p_temp == ' ' && *(p_temp+1) == ' ') //满足此条件停止单词的读取
{
//词性的寻找
while(1)
{
p_temp++;
if(*p_temp != ' ')
break;
}
break;
}
buf_word[i] = *p_temp;
i++; p_temp++;
}
strcpy(buf_mean, p_temp);
buf_mean[strlen(buf_mean)-1] = 0;
//sleep(1);
//printf("%d==%s %s\n",__LINE__, buf_word, buf_mean);
//此时已经可以循环分解开单词和词性以及释义
//写入到数据库中
char temp[128] = "";
sprintf(temp, "insert into dictionary values (\"%s\", \"%s\");", buf_word, buf_mean);
char* errmsg = NULL;
sqlite3_exec(db, temp, NULL, NULL, &errmsg);
}
//关闭数据库,释放内存空间
if(sqlite3_close(db) != SQLITE_OK)
{
fprintf(stderr, "__%d__ sqlite3_close: %d | %s\n", __LINE__, sqlite3_errcode(db), sqlite3_errmsg(db));
return -1;
}
printf("sqlite3_close sucess __%d__\n", __LINE__);
//关闭fopen打开的英文单词只读文件
fclose(fp);
return 0;
}
生成的数据库示例
更多推荐
已为社区贡献1条内容
所有评论(0)