MySQL c++ connector is crashing in debug mode - c++

I started learning mysql c++ connector.
I was trying with sample code given over the internet .
But it is randomly crashing.
It works fine in release mode. But when I use debug mode it is crashing.
Does I need to give (add ) any specific linking option for debug mode ?
/* Standard C++ headers */
#include <iostream>
#include <sstream>
#include <memory>
#include <string>
#include <stdexcept>
/* MySQL Connector/C++ specific headers */
#include <driver.h>
#include <connection.h>
#include <statement.h>
#include <prepared_statement.h>
#include <resultset.h>
#include <metadata.h>
#include <resultset_metadata.h>
#include <exception.h>
#include <warning.h>
#define DBHOST "tcp://127.0.0.1:3306"
#define USER "vivek"
#define PASSWORD "vivek"
#define DATABASE "user2"
#define NUMOFFSET 100
#define COLNAME 200
using namespace std;
using namespace sql;
static void retrieve_data_and_print (ResultSet *rs, int type, int colidx, string colname) {
/* retrieve the row count in the result set */
cout << "\nRetrieved " << rs -> rowsCount() << " row(s)." << endl;
cout << "\nCityName" << endl;
cout << "--------" << endl;
/* fetch the data : retrieve all the rows in the result set */
while (rs->next()) {
if (type == NUMOFFSET) {
cout << rs -> getString(colidx) << endl;
} else if (type == COLNAME) {
cout << rs -> getString(colname) << endl;
} // if-else
} // while
cout << endl;
} // retrieve_data_and_print()
static void retrieve_dbmetadata_and_print (Connection *dbcon) {
if (dbcon -> isClosed()) {
throw runtime_error("DatabaseMetaData FAILURE - database connection closed");
}
cout << "\nDatabase Metadata" << endl;
cout << "-----------------" << endl;
cout << boolalpha;
/* The following commented statement won't work with Connector/C++ 1.0.5 and later */
//auto_ptr < DatabaseMetaData > dbcon_meta (dbcon -> getMetaData());
DatabaseMetaData *dbcon_meta = dbcon -> getMetaData();
cout << "Database Product Name: " << dbcon_meta -> getDatabaseProductName() << endl;
cout << "Database Product Version: " << dbcon_meta -> getDatabaseProductVersion() << endl;
cout << "Database User Name: " << dbcon_meta -> getUserName() << endl << endl;
cout << "Driver name: " << dbcon_meta -> getDriverName() << endl;
cout << "Driver version: " << dbcon_meta -> getDriverVersion() << endl << endl;
cout << "Database in Read-Only Mode?: " << dbcon_meta -> isReadOnly() << endl;
cout << "Supports Transactions?: " << dbcon_meta -> supportsTransactions() << endl;
cout << "Supports DML Transactions only?: " << dbcon_meta -> supportsDataManipulationTransactionsOnly() << endl;
cout << "Supports Batch Updates?: " << dbcon_meta -> supportsBatchUpdates() << endl;
cout << "Supports Outer Joins?: " << dbcon_meta -> supportsOuterJoins() << endl;
cout << "Supports Multiple Transactions?: " << dbcon_meta -> supportsMultipleTransactions() << endl;
cout << "Supports Named Parameters?: " << dbcon_meta -> supportsNamedParameters() << endl;
cout << "Supports Statement Pooling?: " << dbcon_meta -> supportsStatementPooling() << endl;
cout << "Supports Stored Procedures?: " << dbcon_meta -> supportsStoredProcedures() << endl;
cout << "Supports Union?: " << dbcon_meta -> supportsUnion() << endl << endl;
cout << "Maximum Connections: " << dbcon_meta -> getMaxConnections() << endl;
cout << "Maximum Columns per Table: " << dbcon_meta -> getMaxColumnsInTable() << endl;
cout << "Maximum Columns per Index: " << dbcon_meta -> getMaxColumnsInIndex() << endl;
cout << "Maximum Row Size per Table: " << dbcon_meta -> getMaxRowSize() << " bytes" << endl;
cout << "\nDatabase schemas: " << endl;
auto_ptr < ResultSet > rs ( dbcon_meta -> getSchemas());
cout << "\nTotal number of schemas = " << rs -> rowsCount() << endl;
cout << endl;
int row = 1;
while (rs -> next()) {
cout << "\t" << row << ". " << rs -> getString("TABLE_SCHEM") << endl;
++row;
} // while
cout << endl << endl;
} // retrieve_dbmetadata_and_print()
static void retrieve_rsmetadata_and_print (ResultSet *rs) {
if (rs -> rowsCount() == 0) {
throw runtime_error("ResultSetMetaData FAILURE - no records in the result set");
}
cout << "ResultSet Metadata" << endl;
cout << "------------------" << endl;
/* The following commented statement won't work with Connector/C++ 1.0.5 and later */
//auto_ptr < ResultSetMetaData > res_meta ( rs -> getMetaData() );
ResultSetMetaData *res_meta = rs -> getMetaData();
int numcols = res_meta -> getColumnCount();
cout << "\nNumber of columns in the result set = " << numcols << endl << endl;
cout.width(20);
cout << "Column Name/Label";
cout.width(20);
cout << "Column Type";
cout.width(20);
cout << "Column Size" << endl;
for (int i = 0; i < numcols; ++i) {
cout.width(20);
cout << res_meta -> getColumnLabel (i+1);
cout.width(20);
cout << res_meta -> getColumnTypeName (i+1);
cout.width(20);
cout << res_meta -> getColumnDisplaySize (i+1) << endl << endl;
}
cout << "\nColumn \"" << res_meta -> getColumnLabel(1);
cout << "\" belongs to the Table: \"" << res_meta -> getTableName(1);
cout << "\" which belongs to the Schema: \"" << res_meta -> getSchemaName(1) << "\"" << endl << endl;
} // retrieve_rsmetadata_and_print()
int main(int argc, const char *argv[]) {
Driver *driver;
Connection *con;
Statement *stmt;
ResultSet *res;
PreparedStatement *prep_stmt;
Savepoint *savept;
int updatecount = 0;
/* initiate url, user, password and database variables */
string url(argc >= 2 ? argv[1] : DBHOST);
const string user(argc >= 3 ? argv[2] : USER);
const string password(argc >= 4 ? argv[3] : PASSWORD);
const string database(argc >= 5 ? argv[4] : DATABASE);
try {
driver = get_driver_instance();
/* create a database connection using the Driver */
con = driver -> connect(url, user, password);
/* alternate syntax using auto_ptr to create the db connection */
//auto_ptr con (driver -> connect(url, user, password));
/* turn off the autocommit */
con -> setAutoCommit(0);
cout << "\nDatabase connection\'s autocommit mode = " << con -> getAutoCommit() << endl;
/* select appropriate database schema */
con -> setSchema(database);
/* retrieve and display the database metadata */
retrieve_dbmetadata_and_print (con);
/* create a statement object */
stmt = con -> createStatement();
cout << "Executing the Query: \"SELECT * FROM City\" .." << endl;
/* run a query which returns exactly one result set */
res = stmt -> executeQuery ("show datbases");
cout << "Retrieving the result set .." << endl;
/* retrieve the data from the result set and display on stdout */
//retrieve_data_and_print (res, NUMOFFSET, 1, string("CityName"));
con -> commit();
/* Clean up */
delete res;
delete stmt;
delete prep_stmt;
con -> close();
delete con;
} catch (SQLException &e) {
cout << "ERROR: SQLException in " << __FILE__;
cout << " (" << __func__<< ") on line " << __LINE__ << endl;
cout << "ERROR: " << e.what();
cout << " (MySQL error code: " << e.getErrorCode();
cout << ", SQLState: " << e.getSQLState() << ")" << endl;
if (e.getErrorCode() == 1047) {
/*
Error: 1047 SQLSTATE: 08S01 (ER_UNKNOWN_COM_ERROR)
Message: Unknown command
*/
cout << "\nYour server does not seem to support Prepared Statements at all. ";
cout << "Perhaps MYSQL < 4.1?" << endl;
}
return EXIT_FAILURE;
} catch (std::runtime_error &e) {
cout << "ERROR: runtime_error in " << __FILE__;
cout << " (" << __func__ << ") on line " << __LINE__ << endl;
cout << "ERROR: " << e.what() << endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
} // main()

I see a very likely error. The library is creating things for you and you are deleting them.
This could be using a different heap manager and therefore causes problems.
The API is very poor if it does that. It should provide deleters for you. Does it?
I found something like this on their site and told them what I thought:

It happens because the connector uses different version of C++ runtime library than your application. Object created by the connector is initialized differently than the one by your application's library. Then when you destroy the object, you'd be destroying it incorrectly. You'd want to download the source code for the connector and compile it yourself.
To download the source code, go to http://www.mysql.com/downloads/connector/cpp/#downloads and select "source code" for the platform type.

When in debug mode select the debug folder for you libraries instead of opt.

Related

MySQL connector/C++ not working in CodeBlocks

I have installed the latest MySQL connector/c++ 1.1.8 from this site https://dev.mysql.com/downloads/connector/cpp/
this is my main.cpp
#include <iostream>
#include <sstream>
#include <memory>
#include <string>
#include <stdexcept>
#include <stdlib.h>
/* MySQL Connector/C++ specific headers */
#include <driver.h>
#include <connection.h>
#include <statement.h>
#include <prepared_statement.h>
#include <resultset.h>
#include <metadata.h>
#include <resultset_metadata.h>
#include <exception.h>
#include <warning.h>
#define DBHOST "removed"
#define USER "removed"
#define PASSWORD "removed"
#define DATABASE "removed"
#define NUMOFFSET 1
#define COLNAME 1
using namespace std;
using namespace sql;
static void retrieve_data_and_print (ResultSet *rs, int type, int colidx,
string colname)
/* retrieve the row count in the result set */
cout << "\nRetrieved " << rs -> rowsCount() << " row(s)." << endl;
cout << "\nTestColumnName" << endl;
cout << "--------" << endl;
/* fetch the data : retrieve all the rows in the result set */
while (rs->next()) {
if (type == NUMOFFSET) {
cout << rs -> getString(colidx) << endl;
} else if (type == COLNAME) {
cout << rs -> getString(colname) << endl;
} // if-else
} // while
cout << endl;
}
int main(int argc, const char *argv[]) {
Driver *driver;
Connection *con;
Statement *stmt;
ResultSet *res;
PreparedStatement *prep_stmt;
Savepoint *savept;
int updatecount = 0;
/* initiate url, user, password and database variables */
string url(argc >= 2 ? argv[1] : DBHOST);
const string user(argc >= 3 ? argv[2] : USER);
const string password(argc >= 4 ? argv[3] : PASSWORD);
const string database(argc >= 5 ? argv[4] : DATABASE);
try {
driver = get_driver_instance();
/* create a database connection using the Driver */
con = driver -> connect(url, user, password);
/* turn off autocommit */
con -> setAutoCommit(0);
cout << "Database connection\'s autocommit mode = " << con ->
getAutoCommit() << endl;
// select database schema
con -> setSchema(database);
// create a statement object
stmt = con -> createStatement();
cout << "Executing Query: \"SELECT * FROM organizations\" ... " << endl;
/* run query */
res = stmt -> executeQuery ("SELECT * FROM organizations");
cout << "Retrieving the result set ..." << endl;
retrieve_data_and_print (res, NUMOFFSET, 1, string("TestColumnName"));
} catch (SQLException &e) {
cout << "ERROR: SQLException in " << __FILE__;
cout << " (" << __func__<< ") on line " << __LINE__ << endl;
cout << "ERROR: " << e.what();
cout << " (MySQL error code: " << e.getErrorCode();
cout << ", SQLState: " << e.getSQLState() << ")" << endl;
if (e.getErrorCode() == 1047) {
/*
Error: 1047 SQLSTATE: 08S01 (ER_UNKNOWN_COM_ERROR)
Message: Unknown command
*/
cout << "\nYour server does not seem to support Prepared Statements
at all. ";
cout << "Perhaps MYSQL < 4.1?" << endl;
}
return EXIT_FAILURE;
} catch (std::runtime_error &e) {
cout << "ERROR: runtime_error in " << __FILE__;
cout << " (" << __func__ << ") on line " << __LINE__ << endl;
cout << "ERROR: " << e.what() << endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
when i try to build a sample code then this error message appears:
The problem seems to be in the header-files of MySQL connector/c++.
The error displayed by codeblocks is in these header-files
and in this too.
This error is usually related to mingw32 on a 64 bit machine. You would need to use mingw64 http://mingw-w64.org/doku.php/download and set the Toolchain executablables appropriately.

C++ program freezes with 100% CPU in the middle of cout statement

I'm writing a simple graph generator that stores the graphs in a MySQL database.
Here's the output:
Connecting to database...Success!
Checking for unfinished vertices...Completed last n = 7
Creating n8 table...Success!
Notice it doesn't print "Generating..." which is part of the same statement. It freezes just like this with 100% CPU. The table does actually get created in the database.
Also, If I start from n = 1, it runs until n7 and then freezes.
Here's the code (not the entire thing, just this part):
int main()
{
int n = 0;
if (initialize(n)) {
int limit = 8;
if (limit >= n) {
for (; n <= limit; n++) {
stringstream qs;
qs << "CREATE TABLE n" << n << " (idbin TEXT("
<< getLengthOfBinaryByN(n) << ") NOT NULL,vertices INT NOT NULL)";
cout << "Creating n" << n << " table...";
if (runQuery(qs.str())) {
cout << "Success!" << endl
<< "Generating all graphs on " << n << " vertices";
generateGraphs(n);
} else {
cout << "Failed!" << endl;
}
}
} else {
cout << "ERROR: Must be greater than or equal to " << n << endl;
return 1;
}
}
return 0;
}
After some research I found that a "deadlock" may be occurring, but I have no idea how to fix that. Any ideas?
Here's the runQuery function if that helps:
/*
runQuery: runs the sql query, assumes that database connected successfully
Parameters: query
returns a bool
*/
bool runQuery(string query)
{
try {
stmt = con->createStatement();
res = stmt->executeQuery(query);
delete stmt;
} catch (sql::SQLException &e) {
if (e.getErrorCode() != 0 && e.getErrorCode() != 1050) {
cout << "# ERR: SQLException in " << __FILE__
<< "(" << __FUNCTION__ << ") on line " << __LINE__ << endl
<< "# ERR: " << e.what()
<< " (MySQL error code: " << e.getErrorCode()
<< ", SQLState: " << e.getSQLState() << " )" << endl;
return false;
}
return true;
}
return true;
}

Must have pointer to object type c++ (Array)

I have a pointer to object error type for the variable "carrierTime" i have created. If i make this an array, carrierTime becomes an error in the first if statement, however if i leave it without any array i get an error on the last line of the code where i have used carrierTime in a multiplication.
can anyone help??
platform used:visual studios
#include "AMcore.h"
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
using namespace std;
int main()
{
cout << "Amplitude Modulation Coursework" << endl;
cout << "Name: Mohammad Faizan Shah" << endl;
cout << "Student ID: 5526734 \n\n\n" << endl;
std::ifstream file,file2;
string filename1,filename2;
int rowCounter = 0;
double informationTime;
double informationAmplitudeAmount[361];
long double carrierTime;
double carrierAmplitudeAmount[361];
double totalAmplitudeAmount[1000];
int plotPoint;
cout << "Please enter the filename of the Carrier wave \n" << endl;
cin >> filename1;
file.open("carrier.txt");
if (file.is_open())
{
file >> carrierTime;
while (!file.fail())
{
cout << "row" << setw(3) << rowCounter;
cout << " Time = " << setw(5) << carrierTime;
file >> carrierAmplitudeAmount[rowCounter];
rowCounter++;
if (!file.fail())
{
cout << " Carrier signal= " << setw(5) << carrierAmplitudeAmount;
file >> carrierTime;
}
cout << endl;
}
if (file.eof())
cout << "Reached the end of file marker" << endl;
else
cout << "Error whilst reading input file" << endl;
}
else
{
cout << "Error opening input file, ";
cout << "check carrier.txt exists in the current directory." << endl;
}
file.close();
cout << "\n\n" << endl;
cout << "Please enter the filename of the information wave \n\n\n" << endl;
cin >> filename2;
file2.open("information.txt");
if (file2.is_open())
{
file2 >> informationTime;
while (!file2.fail())
{
cout << "row" << setw(3) << rowCounter;
cout << " Time = " << setw(5) << informationTime;
file2 >> informationAmplitudeAmount[361];
rowCounter++;
if (!file2.fail())
{
cout << " Carrier signal= " << setw(5) << informationAmplitudeAmount;
file2 >> informationTime;
}
cout << endl;
}
if (file2.eof())
cout << "Reached the end of file marker" << endl;
else
cout << "Error whilst reading input file" << endl;
}
else
{
cout << "Error opening input file, ";
cout << "check carrier.txt exists in the current directory." << endl;
}
file.close();
cout << "Reading from txt file has completed" << endl << endl;
cout << "\n\n" << endl;
cout << "\n\n" << endl;
cout << "please enter number of sample points to plot:| \n" << endl;
do{
cin >> plotPoint;
if (plotPoint <= 361)
{
cout << "\n plotting the graph.\n" << endl;
}
else if (plotPoint > 361)
{
cout << "Value is too high.. Try value lower than 361\n" << endl;
}
} while (plotPoint > 361);
cout << "row" << setw(3) << rowCounter;
file >> carrierAmplitudeAmount[361];
rowCounter++;
plotPoint = 361 / plotPoint;
cout << " Time \| Amplitude Modulation plot\n------------+--------------------------------------------------\n";
totalAmplitudeAmount[0] = carrierAmplitudeAmount[0] * informationAmplitudeAmount[0];
cout << setw(6) << carrierTime << setw(4) << "\|" << setw(48) << "*" << totalAmplitudeAmount[0] << endl;
for (int i = 1; i <= 361; i = i + plotPoint) {
totalAmplitudeAmount[i] = informationAmplitudeAmount[i] * carrierAmplitudeAmount[i];
int y = totalAmplitudeAmount[i] * 22;
cout << setw(6) << carrierTime[i++] << setw(4) << "\|" << setw(26 + y) << "*" << totalAmplitudeAmount[i] << endl;
}
cout << "End of program" << endl;
system("pause");
return 0;
}
cout << setw(6) << carrierTime[i++] << setw(4) << "\|" << setw(26 + y) << "*" << totalAmplitudeAmount[i] << endl;
carrierTime[i++] does not look correct. The variable is not defined as a pointer.
Also, proper debugging would help you catch these errors for yourself.

GetConsoleSelectionInfo C++

cI want to select some text with my cursor using the Mark Function from Console, but my code doesn't work ...
CONSOLE_SELECTION_INFO c;
if(GetConsoleSelectionInfo(&c))
{
while((c.dwFlags & CONSOLE_MOUSE_DOWN) == 0) { if(c.dwFlags) cout << c.dwFlags; }
cout << "SelectionAnchor: " << c.dwSelectionAnchor.X << " " << c.dwSelectionAnchor.Y;
cout << "RectangleSelection: " << c.srSelection.Top << " " << c.srSelection.Left << c.srSelection.Bottom << c.srSelection.Right;
}
else cout << "\n\nError: " << GetLastError();
Whatever I'm selecting or I'm doing, always c.dwFlags will be 0 ...

getting "undefined reference to `get_driver_instance' "error

I have installed mysql-C++ Connector using Synaptic Package manager.
I am using Ubuntu-12.04
my program is as below as given on Mysql site-
/* Standard C++ headers */
#include <iostream>
#include <sstream>
#include <memory>
#include <string>
#include <stdexcept>
/* 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>
#define DBHOST "tcp://127.0.0.1:8080"
#define USER "root"
#define PASSWORD "231191"
#define DATABASE "test"
#define NUMOFFSET 100
#define COLNAME 200
using namespace std;
using namespace sql;
static void retrieve_data_and_print (ResultSet *rs, int type, int colidx, string colname) {
/* retrieve the row count in the result set */
cout << "\nRetrieved " << rs -> rowsCount() << " row(s)." << endl;
cout << "\nCityName" << endl;
cout << "--------" << endl;
/* fetch the data : retrieve all the rows in the result set */
while (rs->next()) {
if (type == NUMOFFSET) {
cout << rs -> getString(colidx) << endl;
} else if (type == COLNAME) {
cout << rs -> getString(colname) << endl;
} // if-else
} // while
cout << endl;
} // retrieve_data_and_print()
static void retrieve_dbmetadata_and_print (Connection *dbcon) {
if (dbcon -> isClosed()) {
throw runtime_error("DatabaseMetaData FAILURE - database connection closed");
}
cout << "\nDatabase Metadata" << endl;
cout << "-----------------" << endl;
cout << boolalpha;
/* The following commented statement won't work with Connector/C++ 1.0.5 and later */
//auto_ptr < DatabaseMetaData > dbcon_meta (dbcon -> getMetaData());
DatabaseMetaData *dbcon_meta = dbcon -> getMetaData();
cout << "Database Product Name: " << dbcon_meta -> getDatabaseProductName() << endl;
cout << "Database Product Version: " << dbcon_meta -> getDatabaseProductVersion() << endl;
cout << "Database User Name: " << dbcon_meta -> getUserName() << endl << endl;
cout << "Driver name: " << dbcon_meta -> getDriverName() << endl;
cout << "Driver version: " << dbcon_meta -> getDriverVersion() << endl << endl;
cout << "Database in Read-Only Mode?: " << dbcon_meta -> isReadOnly() << endl;
cout << "Supports Transactions?: " << dbcon_meta -> supportsTransactions() << endl;
cout << "Supports DML Transactions only?: " << dbcon_meta -> supportsDataManipulationTransactionsOnly() << endl;
cout << "Supports Batch Updates?: " << dbcon_meta -> supportsBatchUpdates() << endl;
cout << "Supports Outer Joins?: " << dbcon_meta -> supportsOuterJoins() << endl;
cout << "Supports Multiple Transactions?: " << dbcon_meta -> supportsMultipleTransactions() << endl;
cout << "Supports Named Parameters?: " << dbcon_meta -> supportsNamedParameters() << endl;
cout << "Supports Statement Pooling?: " << dbcon_meta -> supportsStatementPooling() << endl;
cout << "Supports Stored Procedures?: " << dbcon_meta -> supportsStoredProcedures() << endl;
cout << "Supports Union?: " << dbcon_meta -> supportsUnion() << endl << endl;
cout << "Maximum Connections: " << dbcon_meta -> getMaxConnections() << endl;
cout << "Maximum Columns per Table: " << dbcon_meta -> getMaxColumnsInTable() << endl;
cout << "Maximum Columns per Index: " << dbcon_meta -> getMaxColumnsInIndex() << endl;
cout << "Maximum Row Size per Table: " << dbcon_meta -> getMaxRowSize() << " bytes" << endl;
cout << "\nDatabase schemas: " << endl;
auto_ptr < ResultSet > rs ( dbcon_meta -> getSchemas());
cout << "\nTotal number of schemas = " << rs -> rowsCount() << endl;
cout << endl;
int row = 1;
while (rs -> next()) {
cout << "\t" << row << ". " << rs -> getString("TABLE_SCHEM") << endl;
++row;
} // while
cout << endl << endl;
} // retrieve_dbmetadata_and_print()
static void retrieve_rsmetadata_and_print (ResultSet *rs) {
if (rs -> rowsCount() == 0) {
throw runtime_error("ResultSetMetaData FAILURE - no records in the result set");
}
cout << "ResultSet Metadata" << endl;
cout << "------------------" << endl;
/* The following commented statement won't work with Connector/C++ 1.0.5 and later */
//auto_ptr < ResultSetMetaData > res_meta ( rs -> getMetaData() );
ResultSetMetaData *res_meta = rs -> getMetaData();
int numcols = res_meta -> getColumnCount();
cout << "\nNumber of columns in the result set = " << numcols << endl << endl;
cout.width(20);
cout << "Column Name/Label";
cout.width(20);
cout << "Column Type";
cout.width(20);
cout << "Column Size" << endl;
for (int i = 0; i < numcols; ++i) {
cout.width(20);
cout << res_meta -> getColumnLabel (i+1);
cout.width(20);
cout << res_meta -> getColumnTypeName (i+1);
cout.width(20);
cout << res_meta -> getColumnDisplaySize (i+1) << endl << endl;
}
cout << "\nColumn \"" << res_meta -> getColumnLabel(1);
cout << "\" belongs to the Table: \"" << res_meta -> getTableName(1);
cout << "\" which belongs to the Schema: \"" << res_meta -> getSchemaName(1) << "\"" << endl << endl;
} // retrieve_rsmetadata_and_print()
int main(int argc, const char *argv[]) {
Driver *driver;
Connection *con;
Statement *stmt;
ResultSet *res;
PreparedStatement *prep_stmt;
Savepoint *savept;
int updatecount = 0;
/* initiate url, user, password and database variables */
string url(argc >= 2 ? argv[1] : DBHOST);
const string user(argc >= 3 ? argv[2] : USER);
const string password(argc >= 4 ? argv[3] : PASSWORD);
const string database(argc >= 5 ? argv[4] : DATABASE);
try {
driver = get_driver_instance();
/* create a database connection using the Driver */
con = driver -> connect(url, user, password);
/* alternate syntax using auto_ptr to create the db connection */
//auto_ptr con (driver -> connect(url, user, password));
/* turn off the autocommit */
con -> setAutoCommit(0);
cout << "\nDatabase connection\'s autocommit mode = " << con -> getAutoCommit() << endl;
/* select appropriate database schema */
con -> setSchema(database);
/* retrieve and display the database metadata */
retrieve_dbmetadata_and_print (con);
/* create a statement object */
stmt = con -> createStatement();
cout << "Executing the Query: \"SELECT * FROM City\" .." << endl;
/* run a query which returns exactly one result set */
res = stmt -> executeQuery ("SELECT * FROM City");
cout << "Retrieving the result set .." << endl;
/* retrieve the data from the result set and display on stdout */
retrieve_data_and_print (res, NUMOFFSET, 1, string("CityName"));
/* retrieve and display the result set metadata */
retrieve_rsmetadata_and_print (res);
cout << "Demonstrating Prepared Statements .. " << endl << endl;
/* insert couple of rows of data into City table using Prepared Statements */
prep_stmt = con -> prepareStatement ("INSERT INTO City (CityName) VALUES (?)");
cout << "\tInserting \"London, UK\" into the table, City .." << endl;
prep_stmt -> setString (1, "London, UK");
updatecount = prep_stmt -> executeUpdate();
cout << "\tCreating a save point \"SAVEPT1\" .." << endl;
savept = con -> setSavepoint ("SAVEPT1");
cout << "\tInserting \"Paris, France\" into the table, City .." << endl;
prep_stmt -> setString (1, "Paris, France");
updatecount = prep_stmt -> executeUpdate();
cout << "\tRolling back until the last save point \"SAVEPT1\" .." << endl;
con -> rollback (savept);
con -> releaseSavepoint (savept);
cout << "\tCommitting outstanding updates to the database .." << endl;
con -> commit();
cout << "\nQuerying the City table again .." << endl;
/* re-use result set object */
res = NULL;
res = stmt -> executeQuery ("SELECT * FROM City");
/* retrieve the data from the result set and display on stdout */
retrieve_data_and_print (res, COLNAME, 1, string ("CityName"));
cout << "Cleaning up the resources .." << endl;
/* Clean up */
delete res;
delete stmt;
delete prep_stmt;
con -> close();
delete con;
} catch (SQLException &e) {
cout << "ERROR: SQLException in " << __FILE__;
cout << " (" << __func__<< ") on line " << __LINE__ << endl;
cout << "ERROR: " << e.what();
cout << " (MySQL error code: " << e.getErrorCode();
cout << ", SQLState: " << e.getSQLState() << ")" << endl;
if (e.getErrorCode() == 1047) {
/*
Error: 1047 SQLSTATE: 08S01 (ER_UNKNOWN_COM_ERROR)
Message: Unknown command
*/
cout << "\nYour server does not seem to support Prepared Statements at all. ";
cout << "Perhaps MYSQL < 4.1?" << endl;
}
return EXIT_FAILURE;
} catch (std::runtime_error &e) {
cout << "ERROR: runtime_error in " << __FILE__;
cout << " (" << __func__ << ") on line " << __LINE__ << endl;
cout << "ERROR: " << e.what() << endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
} // main()
i am using this command to compile:
g++ -I/usr/include/mysql/ -I/usr/include/cppcon/ -L/usr/lib/mysql/ -L/usr/lib -lmysqlclient -lmysqlcppconn MySQLConnectorC++Client.cpp
and getting this as error:
tmp/cc9yx9qf.o: In function main':
MySQLConnectorC++Client.cpp:(.text+0x1060): undefined reference toget_driver_instance'
collect2: ld returned 1 exit status