Skip to content Skip to sidebar Skip to footer

C++ Executequery() Error Displaying Mysql Data From Table

I need some help. I had this code (below), to add data to a MySQL table and then return that same table. The code is doing fine, when I run it it adds the column to the MySQL table

Solution 1:

Check this:

in line:

res = stmt->executeQuery("INSERT INTO "+ table +"(Brand, Model, Power, `Last Used`,`# Times Used`) VALUES('Ferrari','Modena','500','Never',0)");

You are making a wrong string concatenation, that + (plus) operator don't work that way, that code don't concatenate strings, instead is adding pointers.

Just simply replace this way and try again:

#define TABLE "tbex"// put this in top of cpp file
......
res = stmt->executeQuery("INSERT INTO " TABLE "(Brand, Model, Power, `Last Used`
,`# Times Used`) VALUES('Ferrari','Modena','500','Never',0)");

Solution 2:

An INSERT is not a query. Try using executeUpdate() instead of executeQuery().

Replace this line

res = stmt->executeQuery("INSERT INTO "+ table +"(Brand, Model, Power, `Last Used`,`# Times Used`) VALUES('Ferrari','Modena','500','Never',0)"); 

with the following lines (you may need an additional .h file):

sql::PreparedStatement *pstmt;

pstmt = con->prepareStatement("INSERT INTO "+ table +"(Brand, Model, Power, `Last Used`,`# Times Used`) VALUES('Ferrari','Modena','500','Never',0)");
res = pstmt->executeUpdate();
delete pstmt;

Look at the official MySQL example here for an example of the concept.

You may also try using execute(), as shown in this Stackoverflow question. The function execute() is used for generic SQL commands, but may not be as verbose in its return value as more specified functions (it returns a boolean).

Post a Comment for "C++ Executequery() Error Displaying Mysql Data From Table"