SQLite使用C ++插入语句

时间:2012-08-14 04:53:43

标签: c++ sqlite

以下是我在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的某种形式的确认。如果出现错误,它是否也可以出来?

3 个答案:

答案 0 :(得分:2)

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

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

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

或者这个:

INSERT INTO tablename VALUES (value1, value2, value3)

此外,由于您没有将数据绑定到准备好的查询,因此需要引用字符串。仅在panda中替换用户名是不可取的。您需要提供'panda'。因此,字符串就像这样:

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

因为很容易搞砸这个(并且有特殊字符的转义码,例如单引号),你可能更喜欢使用函数引用字符串,它在< em>至少会这样做:

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) + ");";

答案 1 :(得分:1)

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

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 + "');";

答案 2 :(得分:0)

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

包括“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