#include
#include <sqlite3.h>
#include <stdlib.h>
#includevoid do_insert(sqlite3* db, int id, char word[], char jieshi[]);
void txt_todatabase(sqlite3* db);int main(int argc, const char *argv[])
{
if(2 != argc)
{
printf("please %s\n", argv[0]);
return -1;
}
//创建并打开数据库
sqlite3 *db = NULL;
if(sqlite3_open(argv[1], &db) != SQLITE_OK)
{
fprintf(stderr, "line:%d--sqlite3_open:%s\n", __LINE__, sqlite3_errmsg(db));
return -1;
}
printf("database open success\n");//创建表格
char sql[128] = "create table if not exists direct (id int primary key, word char, jieshi char);";
char* errmsg = NULL;if(sqlite3_exec(db, sql, NULL, NULL, &errmsg) != SQLITE_OK)
{
fprintf(stderr, "line:%d-- sqlite3_exec:%s\n", __LINE__, errmsg);
return -1;
}
printf("create table success \n");//将txt中的单词转化为数据库的数据
txt_todatabase(db);//关闭数据库
if(sqlite3_close(db) != SQLITE_OK)
{
fprintf(stderr, "line:%d sqlite3_open:%s\n", __LINE__, sqlite3_errmsg(db));
fprintf(stderr, "line:%d sqlite3_open:%d\n", __LINE__, sqlite3_errcode(db));
return -1;
}
printf("database close success\n");return 0;
}void txt_todatabase(sqlite3* db)
{
char buff[300];//在文件中获取一行
char word[64];//存放单词
char jieshi[256];//存放解释
int id = 0;FILE *fp = fopen("dict.txt", "r");
char *p = NULL;while(NULL != fgets(buff, sizeof(buff), fp))
{//解析出单词和解释
p = buff;
while(1)
{
if(*p == ' ')
{
if(*(p+1) == ' ')
{
break;
}
}
p++;
}
*p = '\0';
p++;//截取单词
strcpy(word, buff);//跳过中间的若干个 空格
while(*p == ' ')
{
p++;
}
//截取解释
strcpy(jieshi, p);
//将数据写入数据库中
id++;
do_insert(db, id, word, jieshi);
}}
void do_insert(sqlite3* db, int id, char word[], char jieshi[])
{
char sql[600] = "";
char* errmsg = NULL;
sprintf(sql, "insert into direct values (%d,\"%s\",\"%s\")", id, word, jieshi);
if(sqlite3_exec(db, sql, NULL, NULL, &errmsg) != SQLITE_OK)
{
fprintf(stderr, "line:%d-- sqlite3_exec:%s\n", __LINE__, errmsg);
return;
}
}