how to insert string into sql query? - c++

below is part of my code,
...
char hashvalue[]="somehash"; // or i can use std::string
SQLCHAR* query = (SQLCHAR*)"SELECT username FROM users WHERE hash = ..." ;
SQLExecDirectA( hStmt, query, SQL_NTS );
...
In the code above I have no idea how to insert into query hashvalue to execute my query like this:
SQLCHAR* query = (SQLCHAR*)"SELECT username FROM users WHERE hash = "somehash"" ;
I 'm very new to sql, thanks in advance for help.

Use std::string
std::string query_string = "SELECT username FROM users WHERE hash = ";
query_string += hashvalue;
SQLExecDirectA(hStmt, query_string.c_str(), SQL_NTS);
Another method:
char query_buffer[1024];
snprintf(query_buffer,
"SELECT username FROM users WHERE hash = %s",
hashValue);
SQLExecDirectA(hStmt, query_buffer, SQL_NTS);
Basically, your question is how to create a formatted string and has nothing to do with SQL.

Related

WHERE column = value, only work with INTEGER value

I use sqlite on a c++ project, but I have a problem when i use WHERE on a column with TEXT values
I created a sqlite database:
CREATE TABLE User( id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(24))
When i try to get the value of the column with VARCHAR values, it doesn't work, and return me a STATUS_CODE 101 just after the sqlite3_step :
int res = 0;
sqlite3_stmt *request;
char *sqlSelection = (char *)"SELECT * FROM User WHERE name='bob' ";
int id = 0;
res = sqlite3_prepare_v2(db, sqlSelection, strlen(sqlSelection), &request, NULL);
if (!res){
while (res == SQLITE_OK || res == SQLITE_ROW){
res = sqlite3_step(request);
if (res == SQLITE_OK || res == SQLITE_ROW ){
id = sqlite3_column_int(request, 0);
printf("User exist %i \n",id);
}
}
sqlite3_finalize(request);
I also tried with LIKE but it also doesn't work
SELECT * FROM User WHERE name LIKE '%bob%'
But when I execute the same code but for an INTERGER value
SELECT * FROM User WHERE id=1
It work fine.
In DB Browser for SQLite all requests work fine.
To solve the problem I searched what status code 101 means.
Here is what they said.
(101) SQLITE_DONE
The SQLITE_DONE result code indicates that an operation has completed.
The SQLITE_DONE result code is most commonly seen as a return value
from sqlite3_step() indicating that the SQL statement has run to
completion. But SQLITE_DONE can also be returned by other multi-step
interfaces such as sqlite3_backup_step().
https://sqlite.org/rescode.html
So, you're getting 101 because there is no more result from SELECT SQL.
The solution was to replace the VARCHAR fields by TEXT.
SQLite for c++ seems to don't manage VARCHAR fields when they are used after the WHERE

SQLite Update table

Trying to update table by user specified values. But the values are not getting updated.
cout<<"\nEnter Ac No"<<endl;
cin>>ac;
cout<<"\nEnter Amount"<<endl;
cin>>amt;
/* Create merged SQL statement */
sql = "UPDATE RECORDS set BAL = '%d' where ACCOUNT_NO = '%d'",amt, ac;
/* Execute SQL statement */
rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg);
If I replace BAL and ACCOUNT_NO by some integer value instead of place holder then it is working fine.
Your sql string is not being created properly.
If you expect this code
sql = "UPDATE RECORDS set BAL = '%d' where ACCOUNT_NO = '%d'",amt, ac;
to result in
"UPDATE RECORDS set BAL = '1' where ACCOUNT_NO = '2'"
where
amt= 1 and ac = 2 then you need to use a string formatting call like this.
// the buffer where your sql statement will live
char sql[1024];
// write the SQL statment with values into the buffer
_snprintf(sql,sizeof(sql)-1, "UPDATE RECORDS set BAL = '%d' where ACCOUNT_NO = '%d'",amt, ac);
buff[sizeof(sql)-1]='\0';
On your particular platform _snprintf(...) might be snprintf(..) or another similarly named function. Also your compiler may warn about buffer manipulation security vulnerabilities. Choose the appropriate substitute for your needs

Querying a MySQL BINARY(8) column, using a std::vector<unsigned char>

I am currently teaching myself C++ (c++0x) so my apologies for any idiocy in this question.
I have an std::vector of length 8 that I want to query in a database to see if it is listed, and if not I will insert it into the database. It's an unsigned char as that is what the base64_decode implementation I have found returns.
This is my query & insert method as it currently stands:
int MySQLConnection::insertByteHash(std::vector<unsigned char> hashSection) {
sql::PreparedStatement *prep_stmt;
sql::ResultSet *res;
prep_stmt = con->prepareStatement("SELECT byteHash_id FROM byteHash WHERE byteHash_content = ? LIMIT 1;");
prep_stmt->setBlob(1, &hashSection);
res = prep_stmt->executeQuery();
if(res->next()){
return res->getInt("byteHash_id");
}
/*
prep_stmt = con->prepareStatement("INSERT INTO byteHash SET byteHash_content = ?;");
prep_stmt->setBlob(1, &str);
res = prep_stmt->executeQuery();
*/
return 1;
}
This is the table in question:
CREATE TABLE `byteHash` (
`byteHash_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`byteHash_content` binary(8) NOT NULL,
PRIMARY KEY (`byteHash_id`),
UNIQUE KEY `UNIQUE_byteHash_content` (`byteHash_content`) USING HASH
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_bin
The binary data as hex is 8FDA7E1F0B56593F.
I was looking into strstream, but keep reading about it being depreciated (not that I managed to get it working anyway), so I am presuming there is a better way to do this.

Trying to modify an sqlite3 insert to return the PK. Wasn't sure how to do it with sqlite3 specifically

I was trying to insert into a table some data, but I wasn't sure what flag allows me to return the primary key. I believe I recall MSSQL using RETURNING, and some others tack on RETURNS at the end.
could someone help out with the appending of it?
I'm trying to return TABLEA.a, and my query and design would look something like this:
sqlite3 *db;
sqlite3_open("...",&db);
std::string query;
query = "insert into TABLEA (b,c,d,e) values (#b,\"#c\",#d,#e);";
//^--this needs to be modified.
sqlite3_stmt *sqlstmt;
int rc;
rc = sqlite3_prepare_v2(db, query.c_str(), 01, &sqlstmt, 0);
sqlite3_step(sqlstmt);
int ID;
ID = sqlite3_column_integer(sqlstmt,0);
Have you tried sqlite3_last_insert_rowid ?

C++ Mysql Real Escape String Issue

Hmm, for some reason, its only doing this on the first username (and password) and does it for how big my my vector is. Any ideas on why?
int eMysql::strip(string &input) {
char* from = new char[strlen(input.c_str()) * 3 + 1];
mysql_real_escape_string(&mysql, from, input.c_str(), input.length());
input = input.assign(from);
delete from;
}
Where its used:
if(query.size() > 0) {
mysql->strip(query[0]);
mysql->strip(query[1]);
mysql->query("SELECT `username` FROM `users` where `username` = '"+ query[0] +"';");
I suggest building the query as a separate string variable rather than passing the mess in the argument:
static const char fixed_text[] = "SELECT `username` FROM `users` where `username` = '";
std::string query_text(fixed_text);
query_text += query[0];
query_text += "';";
mysql->query(query_text);
This technique allows you to examine the query before it is sent to MySql.
I suggest you examine the query[0] variable for any strange characters such as \r and \n. The MySql manual has a section listing characters that need to be escaped.