【发布时间】:2013-04-05 22:25:41
【问题描述】:
我正在尝试将映射的键和值的内容保存到数据库表中。 .dbo 文件已创建,但表中没有任何内容。它不会创建表,但不会退出。我想知道我的代码有什么问题。
void names_table( std::map<std::string, unsigned int> &names ){
std::string sql;
std::string str1;
std::string str2;
std::string str3;
sqlite3_stmt *stmt;
const char *file_names = create_db_file( ); /* default to temp db */
sqlite3 *db;
sqlite3_initialize( );
int rc = sqlite3_open_v2( file_names, &db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL);
if ( rc != SQLITE_OK) {
sqlite3_close( db );
cout << "Error: Database cannot open!" << endl;
exit( EXIT_FAILURE);
}
sql = "CREATE TABLE IF NOT EXISTS names_table (offset INTEGER PRIMARY KEY, stname TEXT);";
sqlite3_prepare_v2(db, sql.c_str(), sql.size(), &stmt, NULL);
if (sqlite3_step(stmt) != SQLITE_DONE) cout << "Didn't Create Table!" << endl;
for (auto pm = names.begin(); pm != names.end(); pm++) {
str2 = "'" + pm->first + "'";
char tmp[15];
sprintf(tmp,"%u",pm->second);
str3 = tmp;
str1 = (((("INSERT INTO names_table VALUES(" + str3) + ", ") + str2) + ");");
std::cout << str1 << std::endl;
sql = (char *)str1.c_str();
// stmt = NULL;
rc = sqlite3_prepare_v2(db, sql.c_str(), sql.size(), &stmt, NULL);
if ( rc != SQLITE_OK) {
sqlite3_close(db);
cout << "Error: Data cannot be inserted!" << endl;
exit ( EXIT_FAILURE);
}
}
sqlite3_close( db );
}
【问题讨论】:
-
exit(-1)不推荐(至少在 C 中) -
谢谢大卫。你对错误处理有什么建议?
-
您的 SQL 语法很可能有一些错误。尝试
std::cout << str1 << std::endl并将其粘贴到此处。另外,第二次调用sqlite3_prepare_v2的返回值是多少? -
@Persianux
exit(EXIT_FAILURE) -
我为 str1 计算出以下语句之一: INSERT INTO names_table VALUES(ramsar, 8329); rc 的返回值为 0