Skip to Main Content

Developer Community

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

MySQL Connector C++ Prepared query

user-aqy3gMay 3 2023

According to the XDevAPI USer Guide, (https://dev.mysql.com/doc/x-devapi-userguide/en/working-with-prepared-statements.html) you can create prepared statements like this:

var f = coll.find("field = :field");
f.bind("field", 1).execute(); // Normal execution
f.bind("field", 2).execute(); // executed with a different parameter value triggers statement preparation
f.bind("field", 3).execute(); // Prepared statement executed with a new value

But this appears to only work on collections. And it is far from clear what that funky field syntax means.

To create prepared statements using relational tables, I made use of the SqlStatement object (which has no default constructor, so you can't create objects of that type within a class.) But I created that object which represents the compiled SQL, in main, where could create an instance of that object, and then passed a pointer from main into my PreparedQuery class where I could set parameters and run the query. This is obviously a kludge, because the SqlStatement object is not supposed to be used, since it isn't even in the class hierarchy reference pages. So my code works like this:

db->open("mygroceries");
//using prepared query
string sqlp = "Select distinct foodname, price, storename from prices \
join foods on(foods.foodkey = prices.foodkey) \
join stores on(stores.storekey = prices.storekey) \
where price > ? and storename like ?";
mysqlx::SqlStatement sqQuery = session→sql(sqlp); //get the statement object
msqPreparedQuery* prep = new msqPreparedQuery(db, &sqQuery);
prep->setVariable(2.0); //set variables
prep->setVariable("S%");
Results* res1 = prep->execute(); //run the query

I don't see another way to do this, although I did bury the creation of the SqlStatement object in my database class.

Are the better ways?

Comments
Post Details
Added on May 3 2023
0 comments
783 views