Page 1 of 1

Syntax for integer variable in an SQL query string, wxSQLite3, C++

Posted: Sat Apr 29, 2017 8:03 pm
by AshtonC1
I'm trying to create a query string for a wxSQLite3 INSERT, DELETE, etc, but I can't get the syntax correct when it includes an 'int' variable.

My code is:

Code: Select all

 //*** Incorrect syntax, compile error ***
 int intAge = 43;
 wxString strSQL = "INSERT INTO user (Name, Age, Country, Position, Phone) VALUES ('" + strName + "','" + intAge + "','" + strCntry + "','" + strPosit + "','" + strPhone + "');";
 
 //***** Works perfectly with an actual value ******
   wxString strSQL = "INSERT INTO user (Name, Age, Country, Position, Phone) VALUES ('" + strName + "', 43,'" + strCntry + "','" + strPosit + "','" + strPhone + "');";
A syntax suggestion greatly appreciated.

Re: Syntax for integer variable in an SQL query string, wxSQLite3, C++

Posted: Sat Apr 29, 2017 11:13 pm
by doublemax
This doesn't work, because integers are not automatically converted to string when using "+".

You can do it like this:

Code: Select all

wxString strSQL;
strSQL << "INSERT INTO user (Name, Age, Country, Position, Phone) VALUES ('" << strName << "','" << intAge << "','" << strCntry << "','" << strPosit << "','" << strPhone + "');";
Or:

Code: Select all

wxString strSQL;
strSQL.Printf("INSERT INTO user (Name, Age, Country, Position, Phone) VALUES ('%s','%d','%s','%s','%s')", strName, intAge, strCntry, strPosit, strPhone );
However, this ignores the fact that certain characters need to be escaped, e.g. the SQL command would fail when strName = "0'Brian". (Because of the ' char).

The cleanest way would be to use wxSQLite3Database::PrepareStatement' together with 'wxSQLite3Statement::Bind', check the wxSQLite3 docs and sample for more information.

Re: Syntax for integer variable in an SQL query string, wxSQLite3, C++

Posted: Mon May 01, 2017 12:07 am
by AshtonC1
Thanks Doublemax that worked perfect.
There were no examples anywhere that I've found using the Bitwise left or right operators.
Amazing.