gpt4 book ai didi

c++:如何使用sqlite3从客户端向数据库中插入值

转载 作者:行者123 更新时间:2023-11-28 08:02:53 32 4
gpt4 key购买 nike

我正在使用这段代码插入数据,但在硬代码中插入数据,但我的需要是使用 c++ 从用户端插入数据,有人能坚持我吗:**

#include <iostream>
using namespace std;
#include "sqlite3.h"
int main (int argc, const char * argv[]) {

sqlite3 *db;
sqlite3_open("test1.db", & db);


string createQuery = "CREATE TABLE IF NOT EXISTS items (userid INTEGER PRIMARY KEY, ipaddr TEXT,username TEXT,useradd TEXT,userphone INTEGER,age INTEGER, "
"time TEXT NOT NULL DEFAULT (NOW()));";
sqlite3_stmt *createStmt;
cout << "Creating Table Statement" << endl;
sqlite3_prepare(db, createQuery.c_str(), createQuery.size(), &createStmt, NULL);
cout << "Stepping Table Statement" << endl;
if (sqlite3_step(createStmt) != SQLITE_DONE) cout << "Didn't Create Table!" << endl;

string insertQuery = "INSERT INTO items (time, ipaddr,username,useradd,userphone,age) VALUES ('', '192.167.37.1','rahul da','benerghatta','9966524824',24);"; // WORKS!
sqlite3_stmt *insertStmt;`enter code here`
cout << "Creating Insert Statement" << endl;
sqlite3_prepare(db, insertQuery.c_str(), insertQuery.size(), &insertStmt, NULL);
cout << "Stepping Insert Statement" << endl;
if (sqlite3_step(insertStmt) != SQLITE_DONE) cout << "Didn't Insert Item!" << endl;

string selectQuery = "select * from items where ipaddr='192.167.37.1' & username= 'rahul';";
sqlite3_stmt *selectStmt;
cout << "Creating select Statement" << endl;
sqlite3_prepare(db, selectQuery.c_str(), selectQuery.size(), &selectStmt, NULL);
cout << "Stepping select Statement" << endl;
if (sqlite3_step(selectStmt) != SQLITE_DONE) cout << "Didn't Select Item!" << endl;

cout << "Success!" << endl;

return 0;
}

最佳答案

这真的取决于你得到的数据存储在什么地方。如果你在特定的变量中得到它,那么你可以使用 std::stringsteam 来实现你想做的事情:

std::stringstream insertQuery;
insertQuery << "INSERT INTO items (time, ipaddr,username,useradd,userphone,age)"
" VALUES ('" << time
<< "', '" << ipaddr
<< "', '" << username
<< "', '" << useradd
<< "', '" << userphone
<< "', " << age << ")";
sqlite3_prepare(db, insertQuery.str().c_str(), insertQuery.size(), &insertStmt, NULL);

注意在字符串流上额外调用 .str() 以返回字符串。

当然,您必须确保您的数据对于要将其插入的列类型有效。如果您的输入直接来自用户,则尤其如此 - 注意常见问题,例如嵌入的引号和元字符。

关于c++:如何使用sqlite3从客户端向数据库中插入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10933301/

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