1.将字典写入数据库中的数据表
代码:
linux@linux:~/study/NETbc$ cat 03_dictsqlite3.c
#include<myhead.h>
#define MAX 50int do_insert(sqlite3* db);int main(int argc, const char *argv[])
{//打开数据库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;}//创建表格char sql[128]="create table if not exists stu (word char,mean char);";char* errmsg=NULL;if(sqlite3_exec(db,sql,NULL,NULL,&errmsg)!=SQLITE_OK){fprintf(stderr,"sqlite3_exec:%s __%d__\n",errmsg,__LINE__);return -1;}printf("create table stu success\n");//调用插入数据函数,创建数据表并将英文字典文本文件的单词和意思导入的数据表中do_insert(db);//关闭数据库if(sqlite3_close(db) != SQLITE_OK){fprintf(stderr,"sqlite3_close:%s %d __%d__\n",\sqlite3_errmsg(db),sqlite3_errcode(db),__LINE__);return -1;}printf("sqlite3_close success\n");return 0;
}//插入数据
int do_insert(sqlite3* db)
{//打开文件操作FILE *fp;fp=fopen("dict.txt","r");char word[MAX]="";char mean[MAX]="";int flag=0; //标志位,用来区别记录单词(0)还是意思(1)int a; //接受fgetc的返回值,必须用int才能取到EFO,直接用char接收会产生段错误。char ch; //记录单个字符while((a=fgetc(fp))!=EOF){ch=a;if(ch=='\n'){//写入数据库操作char sql[128]="";if(snprintf(sql,sizeof(sql),"insert into stu values (\"%s\",\"%s\");",\word,mean) < 0){fprintf(stderr,"snprintf error:__%d__\n",__LINE__);return -1;}char * errmsg=NULL;if(sqlite3_exec(db,sql,NULL,NULL,&errmsg)!=SQLITE_OK){fprintf(stderr,"sqlite3_exec:%s __%d__\n",errmsg,__LINE__);return -1;}bzero(word,sizeof(word)); //给字符串清零bzero(mean,sizeof(mean));flag=0;continue;}else{if(ch==' ') //此文件中,当一行中有一个空格时,就开始收集mean字符串{flag=1;}else if(flag==0){int len=strlen(word);word[len]=ch; //把字符加入字符串中word[len+1]='\0'; //字符串以'\0'结尾}else{int len=strlen(mean);mean[len]=ch; //把字符加入字符串中word[len+1]='\0'; //字符串以'\0'结尾}}}return 0;}
运行结果:
linux@linux:~/study/NETbc$ gcc 03_dictsqlite3.c -lsqlite3
linux@linux:~/study/NETbc$ ./a.out
create table stu success
sqlite3_close success
linux@linux:~/study/NETbc$ sqlitebrowser dict.db