MySQL C++ Connector crashes executing INSERT with BLOB - c++

I've stuck with a problem, trying to insert text as blob value, MySQL C++ connector crashed with exception: "Access violation reading location". I've seen questions like this here, but none has been answered. Here is a code sample:
#include "mysql_connection.h"
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
#include <cppconn/prepared_statement.h>
#include <string>
#include <iostream>
#include <sstream>
using namespace sql;
void main(){
Connection *dbConnection;
Driver *driver;
Connection *con;
driver = get_driver_instance();
con = driver->connect("localhost", "root", "");
Statement *stmt = con->createStatement();
try{
stmt->execute("USE test");
stmt->execute("DROP TABLE blob_test");
stmt->execute("CREATE TABLE blob_test("
"id INTEGER PRIMARY KEY NOT NULL AUTO_INCREMENT,"
"original BLOB NOT NULL);");
char smallBlob[32];
for (char i = 0; i < sizeof(smallBlob); ++i)
{
smallBlob[i] = i;
}
std::istringstream str(smallBlob);
PreparedStatement *pstmt = con->prepareStatement("INSERT INTO blob_test(id, original) VALUES (1, ?)");
pstmt->setBlob( 1, &str);
pstmt->executeUpdate();
}catch(sql::SQLException &e){
std::cerr << "# ERR: " << e.what();
std::cerr << " (MySQL error code: " << e.getErrorCode();
std::cerr << ", SQLState: " << e.getSQLState() << " )" << std::endl;
}
}
Thanks in advance!

Problem solved compiling MySQL cpp connector from sources.
If you go that way read carefully this and this (specially comments in the end). I also had to changed a couple of lines in config.h to implicit cast of int to char*. Also be attentive don't mix Debug and Release, for example if you compile your application in Debug, you should link Debug version of MySQL connector and vice-a-verse.
After I linked lib that I had compiled everything launched )
You may read on dev.mysql.com forums that in most cases it's the only way force the connector to work. While compiling I met with the thing that prove this, include files in source code is different from includes in windows binary distributive.

Related

Connecting the Raspberry Pi 2 with an External Remote Database

I want to connect my Raspberry Pi 2 to an external MySQL database on 000webhost.com with the help of C++.
#include <stdlib.h>
#include <iostream>
#include "mysql_connection.h"
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
using namespace std;
int main(void)
{
try {
sql::Driver *driver;
sql::Connection *con;
sql::Statement *stmt;
sql::ResultSet *res;
/* Create a connection */
driver = get_driver_instance();
con = driver->connect("<000webhost mysql address>", "<username>", "<password>");
/* Connect to the MySQL test database */
con->setSchema("<database>");
stmt = con->createStatement();
res = stmt->executeQuery("<sql statement>"); // replace with your statement
while (res->next()) {
cout << "\t... MySQL replies: ";
/* Access column data by alias or column name */
cout << res->getString("_message") << endl;
cout << "\t... MySQL says it again: ";
/* Access column fata by numeric offset, 1 is the first column */
cout << res->getString(1) << endl;
}
delete res;
delete stmt;
delete con;
} catch (sql::SQLException &e) {
cout << "# ERR: SQLException in " << __FILE__;
cout << "(" << __FUNCTION__ << ") on line " ยป
<< __LINE__ << endl;
cout << "# ERR: " << e.what();
cout << " (MySQL error code: " << e.getErrorCode();
cout << ", SQLState: " << e.getSQLState() << " )" << endl;
}
cout << endl;
return EXIT_SUCCESS;
}
I got an error saying that the mysql_connection.h file was missing. I don't know what i did wrong or if there is an easier or simpler way. Please help me with this matter. Thanks.
I got an error saying that the mysql_connection.h file was missing.
Going by the error message you describe and the response to my question "Do you have the source installed for mysql_connection.h?," which was:
I didn't install mysql on the raspberry pi since I was trying to access an external database.
(Which is not what I asked.) it appears the reason #include "mysql_connection.h doesn't work is because the library isn't there.
The Connector/C library does not require the installation of MySQL, but the Connector/C source must be installed to include headers from the library, according to the documentation.
MySQL's Connector/C library requires boost; however Raspian already has boost installed, though that may come with it's own set of issue, which are discussed and resolved here if you have trouble with boost. (If your Raspberry Pi has NOOBS, I recommend switching to Raspian.)
Though the link is in my comments, instructions for installing the Connector/C library are available from MySQL's documentation.
I've collected some resources and links which should provide some additional help:
How to Install Third Party Libraries
How to #include third party libraries
Installing Connector/C++ from Source on Unix and Unix-Like Systems

res->getString(1) mysql connector crash debug

I have a problem when i use mysql connector c++ and visual studio on the debug mode. It compiles just fine. My algorithm works on release mode. When i switch to debug mode, he complies but he crash while running.
I believe that he crash each time i use res->getString() .
I m using visual studio 2013, mysql connector.C++ 1.1 . I already added the dependencies
C:\Program Files\MySQL\Connector.C++ 1.1\lib\debug
C:\Program Files\Boost SDK;
C:\Program Files\MySQL\Connector.C++ 1.1\include
mysqlcppconn.lib and mysqlcppconn.dll
CPPCONN_PUBLIC_FUNC= ;HAVE_INT8_T=1 ( on the processor definition)
run time library : /MDd ( it the only think that works )
I copied mysqlcppconn.lib and mysqlcppconn.dll in the debug directory of my project
with this configuration my programm works on release mode ( changing Connector.C++ 1.1\lib\debug to Connector.C++ 1.1\lib\opt ).
In the debug mode, he says Debug Assertion failed :
File: f:\dd\vctools\crt\crtw32\misc\dbgheap.c
Line 1322
Expression : _CrtIsValidHeapPointer( pUserData)
Press Rety to debug the application
then i had to choose one buttom ( Ignore; Restart ; leave ). When i press Ignore he continue to run i have the first results but he crashs again
This is my code section
{
#include <stdlib.h>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <memory>
#include <string>
/* MySQL Connector/C++ specific headers */
#include <cppconn/driver.h>
#include <cppconn/connection.h>
#include <cppconn/statement.h>
#include <cppconn/prepared_statement.h>
#include <cppconn/resultset.h>
#include <cppconn/metadata.h>
#include <cppconn/resultset_metadata.h>
#include <cppconn/exception.h>
#include <cppconn/warning.h>
#include "mysql_connection.h"
using namespace std;
using namespace sql;
int main(int argc, const char **argv)
{
const char* str_DataBaseMarketData_Server = "root";
const char* str_DataBaseMarketData_User = "root";
const char* str_DataBaseMarketData_Password ="root";
const char* str_DataBaseMarketData_Database ="bd test";
cout << "Connector/C++ tutorial framework..." << endl;
cout << endl;
string fld;
try {
sql::Driver* driver = get_driver_instance();
std::auto_ptr<sql::Connection> con(driver->connect(str_DataBaseMarketData_Server, str_DataBaseMarketData_User, str_DataBaseMarketData_Password));
con->setSchema(str_DataBaseMarketData_Database);
std::auto_ptr<sql::Statement> stmt(con->createStatement());
sql::SQLString *data = new SQLString();
std::auto_ptr<sql::ResultSet> res(stmt->executeQuery("SELECT * FROM news "));
//ResultSetMetaData *res_meta = res->getMetaData();
//cout << res_meta->getColumnDisplaySize( 1) << endl << endl;
while (res->next()){
fld = res->getString(2).c_str();
}
}
catch (sql::SQLException &e) {
/*
The MySQL Connector/C++ throws three different exceptions:
- sql::MethodNotImplementedException (derived from sql::SQLException)
- sql::InvalidArgumentException (derived from sql::SQLException)
- sql::SQLException (derived from std::runtime_error)
*/
cout << "# ERR: SQLException in " << __FILE__;
cout << "(" << __FUNCTION__ << ") on line " << __LINE__ << endl;
/* Use what() (derived from std::runtime_error) to fetch the error message */
cout << "# ERR: " << e.what();
cout << " (MySQL error code: " << e.getErrorCode();
cout << ", SQLState: " << e.getSQLState() << " )" << endl;
return EXIT_FAILURE;
}
cout << "Done." << endl;
return EXIT_SUCCESS;
}
}
This things turns me crazy because when i replace getString() by anything else, it works sweetly.Could you help me please ?
I m running under a 32 bit.

VS Express 2013 C++ with MySQL Connector stmt->executeQuery() error

So I finally got VS 2013 C++ to connect with mySQL using the Connector C and C++ and I know this because I am able to add a table into my DB using the stmt->execute() function.
Now, I am trying to get the rows using the ResultSet to retrieve from function executeQuery, but this error shows up:
Here is my code:
#include <iostream>
#include <string>
#include "mysql_connection.h"
#include "mysql_driver.h"
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
#include <cppconn/prepared_statement.h>
#define dbHOST "tcp://127.0.0.1:3306"
#define dbUSER "root"
#define dbPASS "root"
#define dbDB "db_test"
using namespace std;
using namespace sql;
int main()
{
sql::mysql::MySQL_Driver *driver;
sql::Connection *con;
sql::Statement *stmt;
sql::ResultSet *res;
driver = sql::mysql::get_driver_instance();
con = driver->connect(dbHOST, dbUSER, dbPASS);
stmt = con->createStatement();
string query = "SELECT * FROM test";
res = stmt->executeQuery(query.c_str());
while (res->next()) {
cout << "id = " << res->getInt(1);
cout << ", label = '" << res->getString("label") << "'" << endl;
}
delete res;
delete stmt;
delete con;
system("pause");
return 0;
}
Under the output pane, it shows this as well:
First-chance exception at 0x77661D4D in MySQLConnect.exe: Microsoft C++ exception: sql::SQLException at memory location 0x0088FB5C.
Unhandled exception at 0x77661D4D in MySQLConnect.exe: Microsoft C++ exception: sql::SQLException at memory location 0x0088FB5C.
Under the call stack after I hit F5 and it breaks, it shows this:
MySQLConnect.exe!main() Line 35 C++
Line 35 is the line with res = stmt->executeQuery(query.c_str());
Let me know if you need more information on my code / settings.
Thanks in advance!
Silly me, I found out what is the problem.
I have to add in a line:
stmt->execute("USE " dbDB);
before I can do any further query for that database. The snippet is now like this:
stmt = con->createStatement();
stmt->execute("USE " dbDB); // <-- This line, change dbDB to your own
string query = "SELECT * FROM test"; // <- before all of these below
res = stmt->executeQuery(query.c_str());
I hope this helps!

exe stopped running error in setting up MySQL C++ connector on Eclipse CDT

We tried running the following code to connect database:
#include <stdlib.h>
#include <iostream>
#include "mysql_connection.h"
#include <cppconn/driver.h>
using namespace sql;
using namespace std;
int main() {
sql::Driver *driver;
cout << "TEST1" << endl;
driver = get_driver_instance();
cout << "TEST2" << endl;
con = driver->connect("TCP:://127.0.0.1:3306", "root", "");
cout << "TEST3" << endl;
}
After building the program successfully, we ran it and encountered the following pop-up message:
"mysql_demo.exe stopped working. A problem caused the program to stop working correctly. Please close the program."
TEST1 and TEST2 are printed successfully on the console, but TEST3 is not.
The platform we use is Windows. We have set up includes and libraries such as mysql server, mysql c++ connector and boost.
I was wondering what the message could indicate. Could anyone help?

/gs option causing program to throw exception

Recently, I've been trying to make a little test program to communicate with a MySQL server in C++. I'm currently using MySQL Connector/C++ as my API to connect to my database server. It took me a very long time to get it running, because oracle/mysql has little to no documentation of how to use connector/c++ with Visual Studio 10+.
Finally after getting everything working, there seems to be some issue when the application tries to exit. It throws the following unhandled exception:
Unhandled exception at 0x00C62291 in mysql2.exe: Stack cookie instrumentation code detected a stack-based buffer overrun.
After researching about the error, I figured out it was due to the "security check" option (/gs compiler option). When I disable this compiler option, the application exits gracefully.
I have a feeling that I should not turn it off, as it is the default option in Visual Studio 2012 (and possibly other versions?)
My questions are:
Why is this /gs compiler option causing the unhandled exception?
Is it safe or okay to turn off the /gs compiler option?
Here is the piece of code the unhandled exception points to (inside a file, called: gs_report.c):
#if defined (_M_IX86) || defined (_M_X64)
if (IsProcessorFeaturePresent(PF_FASTFAIL_AVAILABLE))
#endif /* defined (_M_IX86) || defined (_M_X64) */
__fastfail(FAST_FAIL_STACK_COOKIE_CHECK_FAILURE);
Here is my application code:
/* Standard C++ includes */
#include <stdlib.h>
#include <iostream>
/*
Include directly the different
headers from cppconn/ and mysql_driver.h + mysql_util.h
(and mysql_connection.h). This will reduce your build time!
*/
#include "mysql_connection.h"
#include "mysql_driver.h"
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
#include <cppconn/prepared_statement.h>
using namespace std;
int main(void)
{
cout << endl;
cout << "Let's have MySQL count from 10 to 1..." << endl;
try {
sql::Driver *driver;
sql::Connection *con;
sql::Statement *stmt;
sql::ResultSet *res;
sql::PreparedStatement *pstmt;
/* Create a connection */
driver = sql::mysql::get_driver_instance();
con = driver->connect("tcp://127.0.0.1:3306", "root", "MSxa5y");
/* Connect to the MySQL test database */
con->setSchema("test");
stmt = con->createStatement();
stmt->execute("DROP TABLE IF EXISTS test");
stmt->execute("CREATE TABLE test(id INT)");
delete stmt;
/* '?' is the supported placeholder syntax */
pstmt = con->prepareStatement("INSERT INTO test(id) VALUES (?)");
for (int i = 1; i <= 10; i++) {
pstmt->setInt(1, i);
pstmt->executeUpdate();
}
delete pstmt;
/* Select in ascending order */
pstmt = con->prepareStatement("SELECT id FROM test ORDER BY id ASC");
res = pstmt->executeQuery();
/* Fetch in reverse = descending order! */
res->afterLast();
while (res->previous())
cout << "\t... MySQL counts: " << res->getInt("id") << endl;
delete res;
delete pstmt;
delete con;
} catch (sql::SQLException &e) {
cout << "# ERR: SQLException in " << __FILE__;
cout << "() on line " << __LINE__ << endl;
cout << "# ERR: " << e.what();
cout << " (MySQL error code: " << e.getErrorCode();
cout << ", SQLState: " << e.getSQLState() << " )" << endl;
}
cout << endl;
return EXIT_SUCCESS;
}
The /gs option is allowing the runtime to detect an error in your program. Removing the option allows the program to exit without detecting it, but the error is still there. Somewhere in your code or the libraries, memory on the stack is being overwritten. I'd try a binary search on the code to see which statement is leading to the error. You may also want to always check the return value from all of your database calls.
You definitely should not disable this option. Doing so will hide real errors and may leave your program open to hacking.
Make sure you check the result codes of your method calls. This sounds similar to this question: Buffer Overrun using Mysql Connector c++ as Visual Studio's /gs flag is warning about buffer overflows.