【问题标题】:SQLite Insert Statement with C++使用 C++ 的 SQLite 插入语句
【发布时间】:2012-08-14 04:53:42
【问题描述】:

下面是我在 test2.cpp 上尝试过的代码

我检查了我的数据库,发现没有添加新记录。我的陈述究竟出了什么问题?

#include <iostream>
#include <sqlite3.h>

//g++ -o test2 test2.cpp -lsqlite3
using namespace std;

int main()
{
int counter = 0;

    sqlite3 *db;
    sqlite3_stmt * stmt;

string username = "panda";
string name = "Kungfu Panda";
string department = "normal";
string password = "hellopassword";

string sqlstatement = "INSERT INTO abe_account (" + username + "," + name + "," + department + "," + password + ");";

    if (sqlite3_open("abeserver.db", &db) == SQLITE_OK)
    {
    sqlite3_prepare( db, sqlstatement.c_str(), -1, &stmt, NULL );//preparing the statement
    sqlite3_step( stmt );//executing the statement
        }
    else
    {
        cout << "Failed to open db\n";
    }

    sqlite3_finalize(stmt);
    sqlite3_close(db);


    return 0;

}

我想问是否有可能知道该语句是否也成功执行。就像添加的一行一样,来自 sqlite3 的某种形式的确认。如果有错误,它是否也能cout?

【问题讨论】:

标签: c++ sqlite


【解决方案1】:

当您进行插入时,您通常按照您要提供数据的顺序指定字段。否则,您必须以正确的顺序指定所有数据(按照定义的顺序为表中的所有字段传递一个值)。

因此,您的语法不完整...要么这样做:

INSERT INTO tablename (field1, field2, field3) VALUES (value1, value2, value3);

或者这个:

INSERT INTO tablename VALUES (value1, value2, value3)

此外,由于您没有将数据绑定到准备好的查询,因此您需要引用您的字符串。不能只用panda 代替用户名。您需要提供'panda'。因此,字符串是这样输入的:

"('" + username + "','" + name + "','" + department + "','" + password + "');"

因为这很容易搞砸(并且有特殊字符的转义码,eg 单引号),您可能更喜欢创建一个函数来引用位于 至少会做:

string quotesql( const string& s ) {
    return string("'") + s + string("'");
}

然后:

"(" + quotesql(username) + "," + quotesql(name) + ...

所以,你最终可能会得到这个(假设字段名称):

string sqlstatement =
    "INSERT INTO abe_account (username, name, department, password) VALUES ("
    + quotesql(username) + ","
    + quotesql(name) + ","
    + quotesql(department) + ","
    + quotesql(password) + ");";

【讨论】:

    【解决方案2】:

    尝试在字符串周围添加一些单引号:

    string sqlstatement = "INSERT INTO abe_account ('" + username + "','" + name + "','" + department + "','" + password + ");";
    

    不熟悉sqllite,但通常INSERT看起来像:

    string sqlstatement = "INSERT INTO abe_account (ColumnName1, ColumnName2, ColumnName3, ColumnName4) VALUES ('" + username + "','" + name + "','" + department + "','" + password + "');";
    

    【讨论】:

      【解决方案3】:

      是的,你可以知道它失败的原因。

      包括“sqlite_exception.h”

      按照这个方式:

      int m = sqlite3_step(stmt);
      if(m == SQLITE_BUSY)
      {
      

      /*尝试再次执行 sqlite3_step,使用 sleep() 延迟 **/ }

      if(m == SQLITE_ERROR)
          std::cout(sqlite3_sql(stmt), sqlite3_errmsg(db));
      if(m == SQLITE_MISUSE)
          std::cout(sqlite3_sql(stmt), sqlite3_errmsg(db));
      

      看看这些: http://www.sqlite.org/c3ref/c_abort.html

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-06
        • 2012-04-15
        • 1970-01-01
        • 1970-01-01
        • 2013-06-17
        • 2013-04-10
        相关资源
        最近更新 更多