C++ 和SQLite - 如何执行由用户输入形成的查询
C++ And SQLite - How to execute a query formed by user input?
我正在做一个项目,用户可以在其中将记录插入SQLite数据库。查询将通过以下方式自动生成:
string ID = "";
string title = "";
string password = "";
cout << "Insert ID:n";
cin >> ID;
cout << "Insert title of password:n";
cin >> title;
cout << "Insert password:n";
cin >> password;
string sql = "INSERT INTO test (ID,title,password) VALUES(" + ID + "," + title + "," + password + ");";
当我尝试编译程序时,出现错误:
classes.h:74:76: error: invalid operands of types ‘const char*’ and ‘const char [2]’ to binary ‘operator+’
string sql = "INSERT INTO passwords (ID,title,password) VALUES (" + id + "," + title + "," + password
^
classes.h:78:42: error: invalid operands of types ‘int’ and ‘sqlite3_stmt*’ to binary ‘operator&’
sqlite3_prepare( db, sql.c_str(), -1 &st, NULL);
看来他不能接受多重角色。有人可以告诉我如何解决此错误吗?
附言我是 c++ 的新手
任何帮助,不胜感激。谢谢。
编辑:
完整代码
sqlite3 *db;
sqlite3_stmt * st;
int id = 0;
string title = "";
string password = "";
cout << "Insert ID:n";
cin >> id;
cout << "Insert title of password:n";
cin >> title;
cout << "Insert password:n";
cin >> password;
string sql = "INSERT INTO passwords (ID,title,password) VALUES (" + id + ',' + title + ',' + password + ");";
if(sqlite3_open("pw.db", &db) == SQLITE_OK)
{
sqlite3_prepare( db, sql.c_str(), -1 &st, NULL);
sqlite3_step( st );
}
else
{
cout << "Failed to connectn";
}
sqlite3_finalize(st);
sqlite3_close(db);
应避免直接将用户输入插入 SQL 命令,例如,用户可能会输入恶意文本,故意更改生成的 SQL 语句。
相反,请考虑使用参数绑定,这将允许您避免尝试执行的字符串串联。您的代码:
string sql = "INSERT INTO passwords (ID,title,password) VALUES (" + id + ',' + title + ',' + password + ");";
if(sqlite3_open("pw.db", &db) == SQLITE_OK)
{
sqlite3_prepare( db, sql.c_str(), -1 &st, NULL);
sqlite3_step( st );
}
成为
string sql = "INSERT INTO passwords (ID,title,password) VALUES (?,?,?)";
if(sqlite3_open("pw.db", &db) == SQLITE_OK)
{
sqlite3_prepare( db, sql.c_str(), -1 &st, NULL);
sqlite3_bind_int(st, 1, ID);
sqlite3_bind_text(st, 2, title.c_str(), title.length(), SQLITE_TRANSIENT);
sqlite3_bind_text(st, 3, password.c_str(), password.length(), SQLITE_TRANSIENT);
sqlite3_step( st );
}
1
、2
和3
是从1开始的参数索引。请参阅 https://www.sqlite.org/c3ref/bind_blob.html
错误消息显示 ID 在数据库中声明为 int,但它从 c++ 代码中获取字符串。更改此行:字符串 ID = "; 对此:int ID;
相关文章:
- C++如何通过用户输入删除列表元素
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何使用用户输入在C++中正确填充2D数组
- C++MySQL C api用户输入行
- 用户定义函数中的指针和输入
- 如何只允许用户输入正整数
- C++如何计算用户输入的数字中的偶数位数
- 通过for循环使用用户输入填充列表
- 这是我尝试让用户将值输入到数组中.然后将其隐藏为大量的星号
- 在C++中,我如何接受不同于同一行的用户输入
- 如果用户输入无效,如何使用字符串变量-C++重复输入命令
- 当用户键入分隔符时,停止getline()输入
- 通过错误处理,在C++中可靠地获得用户十六进制输入
- 当用户在qtablewidget中输入单元格时,如何获得信号?C++
- 显示基于用户输入的整数的字符
- 根据用户输入用字母填充矢量,并将"开始"和"结束"放在四肢
- 我试图制作一个程序,要求用户输入问题和答案,但程序循环不正确
- 如果用户没有输入任何内容或输入错误,如何重新输入用户的输入?
- 为什么在代码块中执行时会跳过输入用户输入的行?
- 使用 for 循环在数组中输入用户