c++中,怎么在sqlite中动态添加变量值
阿神
阿神 2017-04-17 11:38:10
[C++讨论组]

int a1 = 1;
int a2 = 10;
char *sqliteInsert = "insert into test123 values("+a1+","+a2+")";
上面的写法是错误的。问题是c++中有没有类似Java中tostring的用法。

阿神
阿神

闭关修行中......

全部回复(4)
天蓬老师
  1. 你的写法为什么是错的? 因为 char* / const char* 类型不支持 + 操作符。你应该使用 std::string.
  2. 有没有类似 JavatoString 的用法? 有。
  • 使用C++11,可以用 std::to_string 方法。
  • C++0x,可以用 stringstream,如 @spacewander 的答案。

c++11:

cpp#include <string>
int a1 = 1;
int a2 = 10;
std::string insertStr = "insert into test123 values(" + std::to_string(a1) + "," + std::to_string(a2) + ")";
char *sqliteInsert = const_cast<char*>(insertStr.c_str());

c++0x:

cpp#include <sstream>
int a1 = 1;
int a2 = 10;
std::ostringstream oss;
oss << "insert into test123 values(" << a1 << "," << a2 << ")";
char *sqliteInsert = const_cast<char*>(oss.str().c_str());

注意:std::string::c_str() 返回值是 const char *,所以直接将其赋值给 char *,编译器可能会给出 error。安全的方式是对其进行 const_cast .

ringa_lee

嗯,你其实是打算问,在C++中怎么把int类型数据转换成string吧?

我觉得最简单的办法,就是用std::stringstream

#include <sstream>

std::stringstream query;
query <<  "insert into test123 values(" << a1 << ", " << a2 << ")";
char *sqliteInsert = query.str().c_str();

更新:我这段代码有问题,query.str().c_str()返回的结果应该进行const_cast,见@pezy 的答案。

PHP中文网

难道不是printf ?

巴扎黑

Binding Values To Prepared Statements (http://www.sqlite.org/c3ref/bind_blob.html)

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号