简体   繁体   English

如何从字符串C ++向sqlite表插入数据?

[英]How to insert a data to sqlite table from a string c++?

I was trying to get some data from user and insert it to sql table. 我试图从用户那里获取一些数据并将其插入到sql表中。 I thought it might be smtg like that but it does not work. 我以为可能是smtg,但它不起作用。 Please tell me how can I add entered in console data to sqlite table? 请告诉我如何将输入的控制台数据添加到sqlite表中?

    string s;
    getline(cin, s);
    cout << s << endl;

    sql = "INSERT INTO Contracts (ID_Con, ID_Shop, ID_Ven, PRICE) "  \
    "VALUES ('%s', s);"; 

/* Execute SQL statement */
   rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg);
   if( rc != SQLITE_OK ){
      fprintf(stderr, "SQL error: %s\n", zErrMsg);
      sqlite3_free(zErrMsg);
   }else{
      fprintf(stdout, "Records created successfully\n");
   }

I thought I can write 1001,2004,5001,50.4 and it will be inputed to "VALUES ('%s', s);" 我以为我可以写1001、2004、5001、50.4,并将其输入到“ VALUES('%s',s);”中。 but it doesn't. 但事实并非如此。 Please help 请帮忙

You can't do parameterised insertion into a string, as you have tried here, in a string assignment operator in C++. 您不能像在此尝试的那样在C ++中的字符串赋值运算符中进行参数化插入字符串。 There are a number of other ways of doing it. 还有许多其他方式可以做到这一点。

You could allocate an old-fashioned C string, and use a sprintf call to substitute your string variable into the resulting string using a %s placeholder. 您可以分配老式的C字符串,并使用sprintf调用使用%s占位符将字符串变量替换为结果字符串。

But I'd probably use a C++ ostringstream to build your string in a more readable way, without all the format string hieroglyphics. 但是我可能会使用C ++ ostringstream以一种更具可读性的方式来构建您的字符串,而没有所有格式的字符串象形文字。 Something like this should do the trick for the example you have above (assuming you have already declared sql as a string): 这样的事情应该可以解决上面的示例(假设您已经将sql声明为字符串):

#include <sstream>

...

string s;
getline(cin, s);
cout << s << endl;

ostringstream oss;

oss << "INSERT INTO Contracts (ID_Con, ID_Shop, ID_Ven, PRICE) "
    << "VALUES ("
    << s
    << ");" ; 

sql = oss.str();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM