C++ 和SQLite - 如何执行由用户输入形成的查询

C++ And SQLite - How to execute a query formed by user input?

本文关键字:输入 用户 查询 执行 SQLite 何执行 C++      更新时间:2023-10-16

我正在做一个项目,用户可以在其中将记录插入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 );
    }

123是从1开始的参数索引。请参阅 https://www.sqlite.org/c3ref/bind_blob.html

错误消息显示 ID 在数据库中声明为 int,但它从 c++ 代码中获取字符串。更改此行:字符串 ID = "; 对此:int ID;