我的 sqlite 数据库只有一张表。这就是我要做的:创建一个包含一个表的数据库,在该表中插入 10,000 条记录,在某些列上创建所需的索引,然后关闭与数据库的连接。我在事务中(在 BEGIN 和 END 之间)将记录插入数据库。我还在插入后创建索引以使插入操作更快。我的问题是:在执行 COMMIT 命令之前是否有任何内容写入磁盘?我需要在内存上创建数据库及其表,在内存上插入记录并再次创建索引,然后一次将所有数据全部写入 dist。我是否使用以下代码实现了我的目的?如果没有,我该如何改进它?
sqlite3 *db;
char *zErrMsg = 0;
int rc;
char sql[500];
/* Open database */
rc = sqlite3_open("test.db", &db);
if( rc ){
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
exit(0);
}else{
fprintf(stderr, "Opened database successfully\n");
}
rc = sqlite3_exec(db, "PRAGMA synchronous = OFF", NULL, NULL, &zErrMsg);
rc = sqlite3_exec(db, "PRAGMA journal_mode = MEMORY", NULL, NULL, &zErrMsg);
rc = sqlite3_exec(db, "BEGIN", NULL, 0, &zErrMsg);
sql = "CREATE TABLE MyTable (Col1 NUMERIC, Col2 NUMERIC, Col3 NUMERIC);";
rc = sqlite3_exec(db, sql, NULL, 0, &zErrMsg);
/* Create SQL statement */
for(int i=0; i<10000; i++)
{
sprintf(sql, "INSERT INTO MyTable (Col1, Col2, Col3, ..., ColN"
"VALUES ( Val1, Val2, Val3, ..., ValN); ");
/* Execute SQL statement */
rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg);
if( rc != SQLITE_OK ){
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
}else{
//fprintf(stdout, "Records created successfully\n");
}
}
sql = "CREATE INDEX ix_Col1 ON MyTable(Col1 ASC);"
"CREATE INDEX ix_Col2 ON MyTable(Col2 ASC);";
rc = sqlite3_exec(db, sql, NULL, 0, &zErrMsg);
rc = sqlite3_exec(db, "COMMIT", NULL, 0, &zErrMsg);
fprintf(stdout, "Records created successfully\n");
sqlite3_close(db);