#include <stdio.h>
#include <sqlite3.h>
#include <stdlib.h>
#include <string.h>
sqlite3* db = NULL;
int id =0;
void do_insert(void)
{
int i;
char eng[20]="";
char sq[70]="";
char chi[50]="";
FILE * fd = fopen("./english.txt","r");
int index = 0;
char * res= NULL;
char sql[100]="";
char * errmsg = NULL;
while(1)
{
id++;
index =0;
bzero(eng,sizeof(eng));
bzero(chi,sizeof(chi));
bzero(sql,sizeof(sql));
res = fgets(sq,sizeof(sql),fd); // 一行行读取数据
if (NULL == res)
{
break;
}
while(1)
{
if (sq[index]==' '&&sq[index+1]==' ')
{
for (i=0;i<index;i++)
{
eng[i]=sq[i];
}
strcpy(chi,sq+2+index);
sprintf(sql,"insert into stu values (%d,\"%s\",\"%s\");",id,eng,chi);
if(sqlite3_exec(db, sql, NULL, NULL, &errmsg) != SQLITE_OK)
{
fprintf(stderr, "__%d__ sqlite3_exec:%s\n", __LINE__, errmsg);
return ;
}
break;
}
index++;
}
}
}
int main(int argc, const char *argv[])
{
//打开数据库
if(sqlite3_open("./dic.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 stu (id int primary key, eng char, chi 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");
do_insert();
//关闭数据库
if(sqlite3_close(db) != SQLITE_OK)
{
printf("err_code:%d\n", sqlite3_errcode(db));
printf("errmsg:%s\n", sqlite3_errmsg(db));
fprintf(stderr, "__%d__ sqlite3_close failed\n", __LINE__);
return -1;
}
printf("sqlite3_close success\n");
return 0;
}
8.17作业
最新推荐文章于 2023-07-30 23:54:49 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)