VS2013 c++ connect mysql --- error in Libmysql.dll - c++

main.cpp
#include "sqlConnection.h"
#include <iostream>
int main() {
sqlConnection *sqlC = new sqlConnection();
sqlC->ifSucceed();
}
sqlConnection.h
#include <Windows.h>
#include <stdio.h>
#include <winsock.h>
#include "mysql.h"
#include <iostream>
#pragma once
using namespace std;
class sqlConnection
{
public:
sqlConnection();
~sqlConnection();
void ifSucceed();
MYSQL mysql;
MYSQL_RES *result;
MYSQL_ROW row;
};
sqlConnection.cpp
#include "sqlConnection.h"
sqlConnection::sqlConnection()
{
mysql_init(&mysql);
mysql_real_connect(&mysql, "xxxxx", "xxxx", "xxxx", "librarySys", 7726, NULL, 0);
}
void sqlConnection::ifSucceed() {
char *sql = "select * from tb_bookcase";
mysql_query(&mysql, sql);
result = mysql_store_result(&mysql);
if ((row = mysql_fetch_row(result)) != NULL) {
cout << "succeed!" << endl;
} else {
cout << "faiiiiiiiiled" << endl;
}
}
sqlConnection::~sqlConnection() {
}
IF there is a libmysql.dll in source file error the message : There
are untreated exception:0x00007FFED00441E6 (libmysql.dll) (in the
librarySys.exe ) 0xC0000005: Access conflict happened when reading
0x0000000000000010.
And then I have to stop. VS give me choice, to change PDB, the binary file path and retry. But I do not know how to do it.
If I delete the libmysql.dll , the error message is:
The program can not be started for losing libmysql.dll in the
computer.Try to reinstall this program to solve this problem.
It's so confusing! I have tried many ways to connect. There are always error messages.

All mysql_* functions return a value that indicates success or failure. Your code disregards them. You ought to confirm whether calls were successful before proceeding to the next call. I surmise you actually failed to connect to the DB and your MYSQL is remains invalid.
Use your debugger. There's no point in coding in the dark. With your debugger you will quickly see whether your MYSQL object has been properly initialized.
Another thing:
sqlConnection *sqlC = new sqlConnection();
There is no reason for this to be heap allocated.

Related

MariaDB connector c ++ memory protection violation

I am having a problem connecting to the database using MariaDB. When I try to do anything with conn, it prints a memory violation.
I use Linux Mint 20.1!!
#include <iostream>
#include <memory>
#include <mariadb/conncpp.hpp>
int main(int argc, char**argv)
{
sql::Driver* driver = sql::mariadb::get_driver_instance();
sql::SQLString url("///");
sql::SQLString base("///");
std::cout << driver->getName() << std::endl;
sql::Properties properties({
{"base", "base"},
{"password", "password"}
});
sql::Connection*conn = driver->connect(url,properties);
conn->setSchema(base);// here
}
Does anyone know what the problem is?
Thank you in advance for your help.
driver->connect may return nullptr. I guess that is happening. You don't check conn.
There is also DriverManager::getConnection, that unlike Driver::connect will throw an exception in such case.

I invoke LSCopyApplicationURLsForURL() using C++, but get a segment fault

I want to write a C++ program to get associated applications which are suitable to open specified file. I find the LSCopyApplicationURLsForURL API, and create a command line C++ application by XCode.
But after running this program, I always get segment fault. XCode shows EXEC_BAD_ACCESS(code=1, address....) error.
I also tryied running it from sudo, but the same result. What is the problem?
The code:
#include <iostream>
#include <objc/objc.h>
#include <objc/objc-runtime.h>
#include <CoreFoundation/CoreFoundation.h>
#include <CoreServices/CoreServices.h>
using namespace std;
int main(int argc, const char * argv[]) {
auto url = CFURLRef("file:///Users/efan/src/a.cpp");
auto ret = LSCopyApplicationURLsForURL(url, kLSRolesAll);
cout << ret << endl;
return 0;
}
Try creating your CFURLRef using one of the proper CFURLCreate* methods. See "Creating a CFURL" here.
For example:
auto tempStringURL = CFStringCreateWithCString(nullptr, "/Users/efan/src/a.cpp", kCFStringEncodingUTF8);
auto url = CFURLCreateWithFileSystemPath(nullptr, tempStringURL, kCFURLPOSIXPathStyle, FALSE);
auto ret = LSCopyApplicationURLsForURL(url, kLSRolesAll);
You need to Release the "Created" variables to clean up memory.

Load csv file into MySQL C++

I'm trying to insert data in a .txt file into MySQL.
Following is the code, I tried so far
#include <stdlib.h>
#include <iostream>
#include <chrono>
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
#include <cppconn/prepared_statement.h>
#define HOST "localhost"
#define USER "root"
#define PASS "admin"
#define DB "test_index"
using namespace std;
int main(int argc, const char **argv)
{
const string url = HOST;
const string user = USER;
const string pass = PASS;
const string database = DB;
sql::Driver *driver = NULL;
sql::Connection *con = NULL;
//sql::Statement *stmt;
sql::ResultSet *res = NULL;
/* Create a connection */
driver = get_driver_instance();
con = driver->connect("tcp://127.0.0.1:3306", "root", "admin");
/* Connect to the MySQL test database */
con->setSchema("test_index");
sql::PreparedStatement *prep_stmt = NULL;
prep_stmt = con->prepareStatement("LOAD DATA INFILE 'C:\ProgramData\MySQL\MySQL Server 8.0\Data\test_index\data.txt' INTO TABLE dataload_file_raw fields terminated by '\t'");
bool ret = prep_stmt->execute();
cout << "The data is inserted" << ret << endl;
delete res;
delete prep_stmt;
con->close();
return 0;
}
The program is failing when it is trying to execute prep_stmt->execute(). Is there any extra configuration I need to do here?
I'm guessing you need to escape the backslashes in your SQL string.
So instead of
"LOAD DATA INFILE 'C:\ProgramData\MySQL..."
You should have
"LOAD DATA INFILE 'C:\\ProgramData\\MySQL..."
Otherwise the C++ compiler will be turning your the '\P' (at the start of ProgramData) into something and '\M' (at the start of MySQL) into something else, which means it'll be trying to hit the wrong path and probably failing because of that. Every backslash in your string will need to be escaped.
You may also want to look into setting up try/catch for the MySQL error reporting, then it'll tell you straightforwardly what went wrong.

MySQL C++ connector program throws error 15

My simple mysql c++ connector program is throwing error 15. What does this mean? The code was taken directly from the online documentation. I can't find the error codes documented anywhere. It's strange because the data ends up getting inserted into the table . Yes i know my statements should be parameterized to avoid SQL injection , this is just a simple test program.
#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 <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("tcp://127.0.0.1:3306", "root", "1092Wilda");
/* Connect to the MySQL test database */
con->setSchema("test");
stmt = con->createStatement();
res = stmt->executeQuery("INSERT INTO bung VALUES ('39', 'TestVal')");
delete res;
delete stmt;
delete con;
} catch (sql::SQLException &e) {
cout << e.getErrorCode();
}
cout << endl;
return EXIT_SUCCESS;
}
after digging around in the header file statement.h i found out that there was a function called executeUpdate (function header below)
virtual int executeUpdate(const sql::SQLString& sql) = 0;
this ended up doing what i wanted to do. program added values into database without throwing any exceptions.
i wish the mySQL C++ connector library wasn't so poorly documented.

fatal error C1083: Cannot open include file: 'boost/variant.hpp': No such file or directory

I'm working on a project due in 2 days, and for the past 2 days, I've just been searching for a way to get this to work. I'm fairly new to C++, and our Class project requires us using C++ to make 5 games, and have them export to a MySQL database for a high scores table.
The MySQL database is no problem at all. My only problem is getting C++ to connect to the MySQL database.
So here's some more info incase someone can help me.
I'm using Visual Studio 2010 and 2012 for this. (As in I have VS 2012, while my school has 2010, so I don't know if there is any compatability differences for this, but I also have VS2010).
I've been searching the web for 5 hours or more about these kind of things, like why my "#include " statement won't work, and I've learned about going into the project properties and adding different include libraries. Usually after surfing for a while, I can figure out where I went wrong, but here I've just hit a dead end, as the only help I can find with this says to include boost, which I have done, but I'm completely stumped to this point. My Friends I'm doing this class project with are getting impatient, as this is the last thing we have left to do.
So here's the things I think I should include.
My Includes for both test programs I am doing (both are the exact same)
"Additional Include Directories"
C:\Users\Damian\Desktop\boost_1_53_0\boost_1_53_0\boost
C:\Program Files\MySQL\MySQL Connector C++ 1.1.3\include
C:\Program Files\MySQL\MySQL Server 5.6\include
My Linker->"Additional Library Directories"
C:\Users\Damian\Desktop\boost_1_53_0\boost_1_53_0\boost
C:\Program Files\MySQL\MySQL Connector C++ 1.1.3\lib\opt
C:\Program Files\MySQL\MySQL Server 5.6\lib
My code for both programs I am trying to run.
This one is the one I was testing on Visual Studio 2012
#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
#include <stdlib.h>
#include <Windows.h>
#include <mysql.h>
#include "mysql_connection.h"
#include <cppconn/driver.h>
#define host "localhost"
#define username "username"
#define password "password"
#define database "db_test"
int main()
{
MYSQL* conn;
conn = mysql_init( NULL );
if( conn )
{
mysql_real_connect( conn, host, username, password, database, 0, NULL, 0 );
}
MYSQL_RES* res_set;
MYSQL_ROW row;
unsigned int i;
mysql_query( conn, "SELECT * FROM tbl_clients WHERE id = 1" );
res_set = mysql_store_result( conn );
unsigned int numrows = mysql_num_rows( res_set );
if( numrows )
{
row = mysql_fetch_row( res_set );
if( row != NULL )
{
cout << "Client ID : " << row[0] << endl;
cout << "Client Name: " << row[1] << endl;
}
}
if( res_set )
{
mysql_free_result( res_set );
}
if( conn )
{
mysql_close( conn );
}
return 0;
}
This is the Code I'm trying to compile on Visual Studio 2010
#include <stdio.h>
#define W32_LEAN_AND_MEAN
#include <winsock2.h>
#include "mysql.h"
#include "mysql_connection.h"
#include <cppconn/driver.h>
#include <iostream>
// change these to suit your setup
#define TABLE_OF_INTEREST "highscores"
#define SERVER_NAME "127.0.0.1"
#define DB_USER "root"
#define DB_USERPASS "root"
#define DB_NAME "test"
// prototypes
void showTables(MYSQL*);
void showContents(MYSQL*,const char*);
using namespace std;
int main(int argc, char* argv[])
{
MYSQL *hnd=NULL; // mysql connection handle
const char *sinf=NULL; // mysql server information
hnd = mysql_init(NULL);
if (NULL == mysql_real_connect(hnd,SERVER_NAME,DB_USER,DB_USERPASS,DB_NAME,0,NULL,0))
{
fprintf(stderr,"Problem encountered connecting to the %s database on %s.\n",DB_NAME,SERVER_NAME);
}
else
{
fprintf(stdout,"Connected to the %s database on %s as user '%s'.\n",DB_NAME,SERVER_NAME,DB_USER);
sinf = mysql_get_server_info(hnd);
if (sinf != NULL)
{
fprintf(stdout,"Got server information: '%s'\n",sinf);
showTables(hnd);
showContents(hnd,TABLE_OF_INTEREST);
}
else
{
fprintf(stderr,"Failed to retrieve the server information string.\n");
}
mysql_close(hnd);
}
return 0;
}
void showTables(MYSQL *handle)
{
MYSQL_RES *result=NULL; // result of asking the database for a listing of its tables
MYSQL_ROW row; // one row from the result set
result = mysql_list_tables(handle,NULL);
row = mysql_fetch_row(result);
fprintf(stdout,"Tables found:\n\n");
while (row)
{
fprintf(stdout,"\t%s\n",row[0]);
row = mysql_fetch_row(result);
}
mysql_free_result(result);
fprintf(stdout,"\nEnd of tables\n");
return;
}
void showContents
(
MYSQL *handle,
const char *tbl
)
{
MYSQL_RES *res=NULL; // result of querying for all rows in table
MYSQL_ROW row; // one row returned
char sql[1024], // sql statement used to get all rows
commastr[2]; // to put commas in the output
int i,numf=0; // number of fields returned from the query
sprintf(sql,"select * from %s",tbl);
fprintf(stdout,"Using sql statement: '%s' to extract all rows from the specified table.\n",sql);
if (!mysql_query(handle,sql))
{
res = mysql_use_result(handle);
if (res)
{
numf = mysql_num_fields(res);
row = mysql_fetch_row(res);
fprintf(stdout,"Rows returned:\n\n");
while (row)
{
commastr[0]=commastr[1]=(char)NULL;
for (i=0;i<numf;i++)
{
if (row == NULL)
{
fprintf(stdout,"%sNULL",commastr);
}
else
{
fprintf(stdout,"%s%s",commastr,row);
}
commastr[0]=',';
}
fprintf(stdout,"\n");
row = mysql_fetch_row(res);
}
fprintf(stdout,"\nEnd of rows\n");
mysql_free_result(res);
}
else
{
fprintf(stderr,"Failed to use the result acquired!\n");
}
}
else
{
fprintf(stderr,"Failed to execute query. Ensure table is valid!\n");
}
return;
}
Now both of these give me this error
1>c:\program files\mysql\mysql connector c++ 1.1.3\include\cppconn\connection.h(31): fatal error C1083: Cannot open include file: 'boost/variant.hpp': No such file or directory
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
Please help! Note: I'm only trying to connect to the database with success so I can run different queries and whatnot. These programs are just tests that I've copied from elsewhere.
Thanks!!
I think
"Additional Include Directories"
C:\Users\Damian\Desktop\boost_1_53_0\boost_1_53_0\boost
needs to be
"Additional Include Directories"
C:\Users\Damian\Desktop\boost_1_53_0\boost_1_53_0