简体   繁体   中英

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[] . 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 :)

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.

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

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++

#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.

buffer2.str().c_str()'

but since this is SQL, using parameters in your query is much better.

Look into sprintf, eg

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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