代码
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sqlite3.h>
int do_insert(sqlite3 *db,char *word,char *mean);
int main(int argc, const char *argv[])
{
//以读的方式打开文件
FILE* fp=fopen("./dict.txt","r");
if(NULL == fp)
{
perror("fopen");
return -1;
}
printf("fopen success\n");
//创建并打开一个数据库
sqlite3 *db = NULL;
if(sqlite3_open("./dict.db",&db) != SQLITE_OK)
{
fprintf(stderr,"sqlite3_open:%s %d __%d__\n",\
sqlite3_errmsg(db),sqlite3_errcode(db),__LINE__);
return -1;
}
printf("open database my.db success\n");
//创建一个表格 create table dict(word char,mean char);
//数据库中sql语句怎么写 这里就怎么写
char sql[128] = "create table if not exists dict(word char,mean char)";
char *errmsg = NULL;
if(sqlite3_exec(db,sql,NULL,NULL,&errmsg) != SQLITE_OK)
{
fprintf(stderr,"sqlite3_exec:%s %d __%d__\n",errmsg,sqlite3_errcode(db
return -1;
}
printf("create table dict success\n");
//定义存放数据的数组
char buf[128]="";
char word[64]="";
char mean[64]="";
char *res=NULL;
while(1)
{
bzero(buf,sizeof(buf));
bzero(word,sizeof(word));
bzero(mean,sizeof(mean));
res=fgets(buf,sizeof(buf),fp);
if(NULL == res)
{
printf("读取完毕\n");
break;
}
char *p=buf;
char *wordp=word;
char *meanp=mean;
while(*p !=' ' || *(p+1) != ' ')
{
if(*p=='\'')
{
*wordp++ ='\'';
p++;
continue;
}
*wordp++ = *p++;
//printf("%c\n",*p);
}
while(*p ==' ')
p++;
while(*p!='\n')
{
*meanp++ = *p++;
}
do_insert(db,word,mean);
}
//关闭数据库
if(sqlite3_close(db) != SQLITE_OK)
{
fprintf(stderr,"sqlite3_close:%s %d __%d__\n",\
sqlite3_errmsg(db),sqlite3_errcode(db),__LINE__);
return -1;
}
printf("close database my.db success\n");
return 0;
}
int do_insert(sqlite3 *db,char *word,char *mean)
{
char sql[128]="";
sprintf(sql,"insert into dict values(\"%s\",\"%s\")",word,mean);
//执行命令
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("insert into dict success \n");
return 0;
}
结果
文章来源地址https://www.toymoban.com/news/detail-652444.html
文章来源:https://www.toymoban.com/news/detail-652444.html
到了这里,关于C语言实现将字典dict.txt上传到数据库中的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!