int ret = mysql_query(&mysql, "insert into books values(20,'er六',25,290,'匿名')"); if (ret) { cout << "Error: Query[添加成功] fail." << endl; break; 如何将这段c++语句中的(20,'er六',25,290,'匿名')用变量来代替 }
时间: 2024-01-18 10:04:21 浏览: 56
可以使用C++字符串和字符串拼接的方式来动态构建SQL语句,如下所示:
```
int id = 20;
string name = "er六";
int price = 25;
int stock = 290;
string author = "匿名";
string sql = "insert into books values(" + to_string(id) + ",'" + name + "'," + to_string(price) + "," + to_string(stock) + ",'" + author + "')";
int ret = mysql_query(&mysql, sql.c_str());
if (ret) {
cout << "Error: Query[添加成功] fail." << endl;
break;
}
```
这样就可以将(20,'er六',25,290,'匿名')中的值用变量来代替了。需要注意的是,字符串需要用单引号括起来,并且在拼接时需要注意字符串和数值类型的转换。
相关问题
int id = 22; string name = "添加书籍"; int number = 20; int price = 10; string author = "添加成功"; printf("请输入I D:"); scanf("%d", &id); printf("请输入书名:"); scanf("%s", &name); printf("请输入数量:"); scanf("%d", &number); printf("请输入价格:"); scanf("%d", &price); printf("请输入作者:"); scanf("%s", &author); printf("测试当前信息---id=%d,name=%s,number=%d,price=%d,author=%s",id,name,number,price,author); string sql = "insert into books values(" + to_string(id) + ",'" + name + "'," + to_string(number) + "," + to_string(price) + ",'" + author + "')"; int ret = mysql_query(&mysql, sql.c_str()); if (ret) { cout << "Error: Query[添加成功] fail." << endl; break; }优化这段c++代码,换一种更好的输出方式
可以使用cout代替printf输出,同时使用<<符号连接字符串和变量,使代码更简洁易懂。优化后的代码如下:
```
int id = 22;
string name = "添加书籍";
int number = 20;
int price = 10;
string author = "添加成功";
cout << "请输入ID:";
cin >> id;
cout << "请输入书名:";
cin >> name;
cout << "请输入数量:";
cin >> number;
cout << "请输入价格:";
cin >> price;
cout << "请输入作者:";
cin >> author;
cout << "测试当前信息---id=" << id << ",name=" << name << ",number=" << number << ",price=" << price << ",author=" << author << endl;
string sql = "insert into books values(" + to_string(id) + ",'" + name + "'," + to_string(number) + "," + to_string(price) + ",'" + author + "')";
int ret = mysql_query(&mysql, sql.c_str());
if (ret) {
cout << "Error: Query[添加成功] fail." << endl;
break;
}
```
阅读全文