gpt4 book ai didi

c++ - 使用 C++ 的 SQLite 插入语句

转载 作者:搜寻专家 更新时间:2023-10-31 01:52:52 25 4
gpt4 key购买 nike

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

最佳答案

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

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

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

或者这个:

INSERT INTO tablename VALUES (value1, value2, value3)

此外,因为您没有将数据绑定(bind)到准备好的查询,所以您需要引用您的字符串。仅仅用 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) + ");";

关于c++ - 使用 C++ 的 SQLite 插入语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11945980/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com