我正在开发一个项目,用户可以将记录插入 SQLite 数据库。\n查询将通过以下方法自动生成:
\n\nstring ID = "";\nstring title = "";\nstring password = "";\n\ncout << "Insert ID:\\n";\ncin >> ID;\ncout << "Insert title of password:\\n";\ncin >> title;\ncout << "Insert password:\\n";\ncin >> password;\n\nstring sql = "INSERT INTO test (ID,title,password) VALUES(" + ID + "," + title + "," + password + ");";\nRun Code Online (Sandbox Code Playgroud)\n\n当我尝试编译该程序时,出现错误:
\n\n classes.h:74:76: error: invalid operands of types \xe2\x80\x98const char*\xe2\x80\x99 and \xe2\x80\x98const char [2]\xe2\x80\x99 to binary \xe2\x80\x98operator+\xe2\x80\x99\n string sql = "INSERT INTO passwords (ID,title,password) VALUES (" + id + "," + title + "," + password \n ^\nclasses.h:78:42: error: invalid operands of types \xe2\x80\x98int\xe2\x80\x99 and \xe2\x80\x98sqlite3_stmt*\xe2\x80\x99 to binary \xe2\x80\x98operator&\xe2\x80\x99\n sqlite3_prepare( db, sql.c_str(), -1 &st, NULL);\nRun Code Online (Sandbox Code Playgroud)\n\n似乎他不能接受多个字符。\n有人可以告诉我如何修复此错误吗?
\n\nPS 我是 C++ 新手
\n\n任何帮助表示赞赏。谢谢。
\n\n编辑:
\n\n完整代码
\n\nsqlite3 *db;\nsqlite3_stmt * st;\nint id = 0;\nstring title = "";\nstring password = "";\n\ncout << "Insert ID:\\n";\n cin >> id;\n cout << "Insert title of password:\\n";\n cin >> title;\n cout << "Insert password:\\n";\n cin >> password;\n\n string sql = "INSERT INTO passwords (ID,title,password) VALUES (" + id + \',\' + title + \',\' + password + ");";\n\n if(sqlite3_open("pw.db", &db) == SQLITE_OK)\n {\n sqlite3_prepare( db, sql.c_str(), -1 &st, NULL);\n sqlite3_step( st );\n }\n else\n {\n cout << "Failed to connect\\n";\n }\nsqlite3_finalize(st);\nsqlite3_close(db);\nRun Code Online (Sandbox Code Playgroud)\n
您应该避免像这样直接将用户输入插入到 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 );
}
Run Code Online (Sandbox Code Playgroud)
变成
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 );
}
Run Code Online (Sandbox Code Playgroud)
、1和是从 1 开始的参数索引2。3请参阅https://www.sqlite.org/c3ref/bind_blob.html