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

This forum can be used to talk about general design strategies, new ideas and questions in general related to wxWidgets. If you feel your questions doesn't fit anywhere, put it here.
Post Reply
AshtonC1
Earned some good credits
Earned some good credits
Posts: 100
Joined: Wed Feb 18, 2015 4:56 pm

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

Post by AshtonC1 » Sat Apr 29, 2017 8:03 pm

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.

User avatar
doublemax
Moderator
Moderator
Posts: 13992
Joined: Fri Apr 21, 2006 8:03 pm
Location: $FCE2

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

Post by doublemax » Sat Apr 29, 2017 11:13 pm

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.
Use the source, Luke!

AshtonC1
Earned some good credits
Earned some good credits
Posts: 100
Joined: Wed Feb 18, 2015 4:56 pm

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

Post by AshtonC1 » Mon May 01, 2017 12:07 am

Thanks Doublemax that worked perfect.
There were no examples anywhere that I've found using the Bitwise left or right operators.
Amazing.

Post Reply