简体   繁体   English

C ++中的Char数组,并将其与其他数组合并

[英]Char array at c++ and merge it with other

I want to add some variable to char array while creating it. 我想在创建字符数组时向其添加一些变量。 How can I do this? 我怎样才能做到这一点? sqlite3_prepare_v2 need char[] . sqlite3_prepare_v2需要char[] thanks 谢谢

unsigned int keyid = 10;
char buffer2[] = "SELECT * FROM table WHERE id = " + keyid; // problem (convert to char and merge)
sqlite3_prepare_v2(db, buffer2, strlen(buffer2), &stmt, 0);

Put the string inside a string :) 将字符串放在string :)

std::string buffer2 = "SELECT * FROM table WHERE id = " + std::to_string(keyid);
sqlite3_prepare_v2(db, buffer2.c_str(), buffer2.length(), &stmt, 0);

You should be binding your parameter instead. 您应该改为绑定参数。 This also prevents any potential for SQL injection attacks. 这也可以防止任何潜在的SQL注入攻击。

unsigned int keyid = 10;
const char buffer2[] = "SELECT * FROM table WHERE id = ?";
sqlite3_prepare_v2(db, buffer2, -1, &stmt, 0);
sqlite3_bind_int(&stmt, 1, keyid);

Well the most obvious solution for C++ is to use std::string 好吧,最明显的C ++解决方案是使用std::string

std::string buffer2 = "SELECT * FROM table WHERE id = " + std::to_string(keyid);
sqlite3_prepare_v2(db, buffer2.c_str() , buffer2.size() , &stmt, 0);

You could stream the different types since you are using C++ 由于使用的是C ++,因此可以流式传输不同的类型

#include <sstream>
//...
std::stringstream buffer2;
buffer2 << "SELECT * FROM table WHERE id = " << keyid;

and then use the string's c_str where ac style string is needed. 然后在需要ac样式字符串的地方使用字符串的c_str

buffer2.str().c_str()'

but since this is SQL, using parameters in your query is much better. 但是由于这是SQL,因此在查询中使用参数要好得多。

Look into sprintf, eg 查看sprintf,例如

sprintf(buffer2, "SELECT * FROM table WHERE id = %d", keyID);

http://www.cplusplus.com/reference/cstdio/sprintf/ http://www.cplusplus.com/reference/cstdio/sprintf/

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

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