SQLITE3在C中制作加载文件

时间:2014-05-04 20:11:43

标签: sql c sqlite

我第一次使用sqlite 3,并且我正在尝试构建一个加载文件来从CSV文件中读取信息并将其存储到表中。我认为它最初删除表是好的,但是当我尝试添加时,我收到了我写的错误消息"不确定我们从步骤"有人可以看一眼我的代码并告诉我,我是否遗漏了一些明显的东西?感谢

编辑:if语句中的比较为SQLITE_DONE输出101,为sqlite3_step(sqlstate)输出21,但我找不到文档来理解这些代码。

#include <stdio.h>
#include <sqlite3.h>
#include <string.h>

#define MAX_LINE 200

int main(int argc, char** argv)
{
  sqlite3 *db;
  int rc;

  if(argc != 4)
    {
      fprintf(stderr, "USAGE: %s <database file> <table name> <CSV file>\n", argv[0]);
      return 1;
    }

    rc = sqlite3_open(argv[1], &db);
    if(rc)
    {
        fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
        sqlite3_close(db);
        return(1);
    }
    sqlite3_stmt *sqlstate;

    if(sqlite3_prepare(db, "DELETE FROM mytable", -1, &sqlstate, 0) == SQLITE_OK)
    {
        if(SQLITE_DONE != sqlite3_step(sqlstate))
        {
            printf("Not sure what response we got from step");
            sqlite3_close(db);
        }
    }

    FILE *f = fopen(argv[3], "r");
    char line[MAX_LINE];

    while(fgets(line, MAX_LINE, f) != NULL)
    {
        char query[MAX_LINE] = "INSERT INTO ";
        strcat( query, argv[2]);
        strcat( query, " VALUES (");
        strcat( query, line);
        strcat( query, " );");

        if(sqlite3_prepare(db, query, -1, &sqlstate, 0) == SQLITE_OK)
        {
            if(SQLITE_DONE != sqlite3_step(sqlstate))
            {
                printf("Not sure what response we got from step DONE");
                sqlite3_close(db);
            }
            if(SQLITE_DONE != sqlite3_step(sqlstate))
            {
                printf("Not sure what response we got from step DONE1");
                sqlite3_close(db);
            }
        }
    }
  fclose(f);
  return 0;
}

0 个答案:

没有答案