c++ - 数据未插入 sqlite 表 c++

标签 c++ c database sqlite

我正在尝试将映射的键和值的内容保存到数据库表中。创建了 .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 );

最佳答案

INSERT INTO names_table VALUES(ramsar, 8329) - 我希望您知道 SQL 中的字符串文字需要用引号引起来。试试这个:INSERT INTO names_table VALUES('ramsar', 8329)

编辑:实际上,您的代码永远不会执行您想要的操作,因为您甚至没有调用 sqlite3_stepsqlite3_prepare_v2 之后,这意味着您只是在编译 SQL 语句,而不是对其求值。你在哪里找到这个坏例子?参见 herehere关于如何正确使用 SQLite C++ 接口(interface)的不错示例。

PS:停止在 C++ 中乱用 sprintf。你有 std::stringstream

关于c++ - 数据未插入 sqlite 表 c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15816846/

相关文章:

c++ - 放置新的和非默认的构造函数

c - 在 C 中释放内存时出现段错误

c++ - GLUPerspective 的原始 OpenGL 等价物?

Linux - 自动完成提示数据库密码

java - 如何选择Firebase实时数据库中的键名称?

c++ - 在可变参数模板类中初始化静态数组

c++ - 临时对象没有被正确销毁?

c++ - 有没有办法强制 C++ 编译器将变量存储在寄存器中?

c - 散列表搜索比链表搜索慢

xml - 基于 XML 或数据库结构的 Flex 代码生成器