2016-04-23 54 views
1

我正在处理用户可以将记录插入到SQLite数据库的项目。 查询会在下面的方法自动生成:C++和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); 
+1

永远不会使用原始用户输入来形成sql查询,除非您的目的是为了说明为什么它是一个坏主意。我不在乎它是否是一些玩具项目。 – Yakk

+0

是的,这是一个供个人使用的项目。 – CMz

+1

'std :: to_string(id)'(假设这篇文章中最后一段代码是* actual *问题,其中'id'确实被声明为'int')。 – WhozCraig

回答

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); 
    } 

123是基于1的参数指标。请参阅https://www.sqlite.org/c3ref/bind_blob.html

-1

你的错误信息显示,ID被声明为数据库中的INT,但它会从你的C++代码的字符串。改变这一行:string ID =“”;为此:int ID;

+0

该id被声明为一个整数...无论如何我添加了完整的代码 – CMz

+0

还检查语句中的引号。字符串sql =“INSERT INTO密码(ID,标题,密码)VALUES('”+ id +“','”+ title +“','”+ password +“');”; –

+0

刚发现一些有用的东西http://stackoverflow.com/questions/11945980/sqlite-insert-statement-with-c –

0

提示:

string str1 = "Chris";  
string res = string("hello ") + str1;