我正在开发一个用户可以将记录插入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);
似乎他不能接受多重角色。
有人可以告诉我如何解决这个错误吗?
P.S。我是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 connect\n";
}
sqlite3_finalize(st);
sqlite3_close(db);
答案 0 :(得分:3)
您应该避免直接将用户输入插入到这样的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
答案 1 :(得分:0)
提示:
string str1 = "Chris";
string res = string("hello ") + str1;
答案 2 :(得分:-1)
您的错误消息显示该ID在数据库中声明为int,但它从您的c ++代码中获取一个字符串。改变这一行:string ID =&#34;&#34 ;;对此:int ID;