how connect mysql using c++ - c++

Editor's Note: Original Text:
how connect mysql using c++
#include <iostream>
#include <fstream>
#include <string>
#include "/usr/local/mysql5/include/mysql.h"
using namespace std;
int main() {
MYSQL *mysql;
MYSQL_RES *result;
MYSQL_ROW row;
string server = "192.168.1.92";
string username = "useradmin";
string password = "useradmin";
string database = "market";
int port = 3306;
mysql = mysql_init(0);
if ( !mysql_real_connect( mysql, server.c_str(), username.c_str(), password.c_str(), database.c_str(), port, NULL, 0 ) ) {
fprintf( stderr, "%s\n", mysql_error( mysql ) );
return 0;
}
if ( !mysql_query( mysql, "SELECT text, prequency FROM ma_dict" ) ) {
fprintf(stderr, "%s\n", mysql_error( mysql ) );
return 0;
}
result = mysql_use_result( mysql );
ofstream SaveFile("/tmp/dict.txt");
while ( ( row = mysql_fetch_row( result ) ) != NULL ) {
//SaveFile << fprintf( stdout, "%s\t%d", row[0], $row[1] ) << endl;
cout << row[0] << endl;
}
mysql_free_result( result );
mysql_close( mysql );
SaveFile.close();
return 1;
}
undefined reference to mysql_init'
undefined reference tomysql_real_connect'
...
Editor's Note: A translation was attempted:
I'm using Eclipse, and I get compilation errors using mysql.h. How do I link to mysql?
#include "mysql.h"
Editor's Note: English questions are required on Stack Overflow. Please do your best at translating your question to English as needed, even if you have to use an automatic translation service like Google Translate.

Editor's Note: Original Text:
信息太少了, 把编译器错误贴出来看看.
可能因为:
mysql.h不在配置的include目录中.
Mysql库文件不在link列表里面
头文件与二进制库文件不配套
Editor's Note: A translation was attempted:
There's too little information in your question. Post the actual compiler error into your question.
That being said, the error may be caused by:
Mysql.h is not in the configuration or in the include directory.
MySql database file is not in the linker's path.
Header and library files are not consistent with each other.

An issue in the sample is that mysql_query returns 0 on SUCCESS – so it always thinks an error occurred on success.
Change it to:
if ( mysql_query( mysql, "SELECT text, prequency FROM ma_dict" ) ) {

Related

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

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.

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

Mysql 5.5 LOAD DATA INFILE Permissions

ERROR The used command is not allowed with this MySQL version
I am having problems migrating some mysqlclient C++ code from Mysql 5.1 to 5.5 (using soci). The C++ part is not so relevant - the problem is writing some mysqlclient code which can successfully do a LOAD DATA INFILE on MySQL 5.5.
Here are my notes (LOAD DATA INFILE fails, but normal queries are ok):
The code below works fine on Mysql 5.1, gcc 4.6.1, Oneiric
The same code fails on Mysql 5.5, gcc 4.7.2, Quantal
If I LOAD DATA INFILE from mysql (the command-line client), it works fine (I have updated my.cnf with local-infile=1)
mysql> show variables like '%local_infile%'; results in ON
It would be great if there were a SOCI or a configuration solution to this, but if someone has managed to get this to work with libmysqlclient, that would be great to know, too...
#include <soci.h>
#include <mysql/soci-mysql.h>
#include <string>
#include <iostream>
using soci::use;
using namespace std;
using namespace soci;
main()
{
string val =
"mysql://" +
"host=127.0.0.1" +
" dbname=tmp_db" +
" user=root" +
" password=open_sasame";
int sum;
session sql( val );
sql << "SELECT 1+1", into( sum );
cerr << "RESULT=" << sum << endl; // works fine
// NEXT LINE FAILS WITH:
// The used command is not allowed with this MySQL version
sql << "LOAD DATA LOCAL INFILE '/tmp/junk3.txt' INTO TABLE tmp_db.example_tbl FIELDS TERMINATED BY '|' LINES TERMINATED BY '\\n'";
}
The answer is, we need the following line of code:
mysql_options( &mysql, MYSQL_OPT_LOCAL_INFILE, 0 );
inserted between mysql_init() and mysql_real_connect().
Below is a snippet of C code for reference. Note that SOCI's mysql backend can be patched with this line of code for it to work.
Tested and works on Mysql 5.5, gcc 4.7.2, Quantal.
#include <mysql.h>
#include <stdio.h>
main()
{
MYSQL mysql;
mysql_init( &mysql );
mysql_options( &mysql, MYSQL_OPT_LOCAL_INFILE, 0 );
if ( !mysql_real_connect( &mysql,"127.0.0.1","root","open_sasame","tmp_db",0,NULL,0 ))
{
fprintf(stderr, "Failed to connect to database: Error: %s\n",
mysql_error( &mysql ));
}
if ( mysql_query( &mysql, "LOAD DATA LOCAL INFILE '/tmp/junk4.txt' "
"INTO TABLE tmp_db.example_tbl FIELDS TERMINATED BY '|' "
"LINES TERMINATED BY '\\n'" ))
{
fprintf( stderr, "ERROR DURING LOAD DATA LOCAL INFILE\n" );
}
mysql_close( &mysql );
}

mysql_query does not save data properly

#include <iostream>
#include <Windows.h>
#include <mysql.h>
#include <string>
#include <stdio.h>
using namespace std;
MYSQL *connection, mysql;
MYSQL_RES *result;
MYSQL_ROW row;
int query_state;
int main(int argc, char** argv)
{
setlocale(LC_ALL, "");
mysql_init(&mysql);
mysql_real_connect(&mysql,"xxx","xxx","xxx","xxx",0,0,0);
mysql_options(&mysql, MYSQL_SET_CHARSET_NAME, "utf8");
mysql_options(&mysql, MYSQL_INIT_COMMAND, "SET NAMES 'utf8' [COLLATE 'utf8_slovak_ci']");
mysql_query(&mysql, "SELECT priezvisko FROM tour_pouzivatelia WHERE id_pouz=5");
result = mysql_store_result(&mysql);
if ((row = mysql_fetch_row(result)) != NULL) {
string sql;
sql = "UPDATE tour_pouzivatelia SET priezvisko='";
sql += row[0];
sql += "' WHERE id_pouz=2";
char* s = new char[sql.length()];
strcpy(s, sql.c_str());
mysql_query(&mysql, s);
}
getchar();
return 0;
}
The value in the database is +ľščťžýáíéô§ň, the tables have charset utf8 and ut8_slovak_ci collation
Yet the following code saves the result as +¾šèžýáíéúäô§ò.
I'm using Visual studio 2010 c++ express.
The problem seems to be that mysql_query does not handle the sql passed to it, it removes the specific characters like š,č,ľ. I've tried many conversions, the function itself however requires the sql to be as const char *.
Is there any way to make this work, so that the char * variable will save the given characters correctly?
If I read the values from database they show up correctly...
Before any DML, try to issue SET names utf8 query (or other which you need)

Connecting to MS Access database using C++ using Visual Studio 2008

I need some serious help trying to connect to an Access database using VS 2008's C++. I have done this in C# but I cant figure this out in C++. I need to use C++ for the connection because I am grabbing data using pre-compiled C++ code. I would really appreciate some help with this. Thanks
I would like to odbc, but if you have another recommendation then I could change my mind.I am trying to connect to an Access database, the Northwind sample database, by following this example,
http://msdn.microsoft.com/en-us/library/cc811599.aspx
I am using a Windows 7 OS with Visual C++ 2008 for the compiler and IDE. The program is a console application. This example is specified for Access 2007 .accdb file types. Once I get it running correctly I will switch the path name, queries, and table names to my database. Below is the code that fails to build. I don't know what is causing this:
Includes-->
fstream
cmath
complex
iostream
iomanip
vector
limits
stdlib.h
stdio.h
time.h
fcntl.h
string.h
ctype.h
icrsint.h
using namespace std;
#import C:\\Program Files\\Common Files\\system\\ado\\msado15.dll rename("EOF",
"AdoNSEOF")
_bstr_t bstrConnect="Provider=Microsoft.ACE.OLEDB.12.0;Data "
"Source=C:\\Users\\lriley\\Documents\\Northwind 2007.mdb;";
HRESULT hr;
int main()
{
::CoInitialize(NULL);
const char* DAM = "ADO";
ADODB::_ConnectionPtr pConn("ADODB.Connection");
hr = pConn->Open(bstrConnect, "admin", "", ADODB::adConnectUnspecified);
if(SUCCEEDED(hr))
{
cout<<DAM<<": Successfully connected to database. Data source name:\n "
<<pConn->GetConnectionString()<<endl;
// Prepare SQL query
_bstr_t query = "SELECT Customers.[Company], Customers.[First Name] FROM "
"Customers;";
cout <<DAM<<": SQL query \n "<<query<<endl;
// Execute
ADODB::_RecordsetPtr pRS("ADODB.Recordset");
hr = pRS->Open(query,
_variant_t((IDispatch *) pConn, true),
ADODB::adOpenUnspecified,
ADODB::adLockUnspecified,
ADODB::adCmdText);
if(SUCCEEDED(hr))
{
cout<<DAM<<": Retrieve schema info for the given result set: "<< endl;
ADODB::Fields* pFields = NULL;
hr = pRS->get_Fields(&pFields);
if(SUCCEEDED(hr) && pFields && pFields->GetCount() > 0)
{
for(long nIndex=0; nIndex < pFields->GetCount(); nIndex++)
{
cout << " | "<<_bstr_t(pFields->GetItem(nIndex)->GetName());
}
cout << endl;
}
else
{
cout << DAM << ": Error: Number of fields in the " <<
"result is set to zero." << endl;
}
cout<<DAM<<": Fetch the actual data: " << endl;
int rowCount = 0;
while (!pRS->AdoNSEOF)
{
for(long nIndex=0; nIndex < pFields->GetCount(); nIndex++)
{
cout<<" | "<<_bstr_t(pFields->GetItem(nIndex)->GetValue());
}
cout<< endl;
pRS->MoveNext();
rowCount++;
}
cout<<DAM<<": Total Row Count: " << rowCount << endl;
}
pRS->Close();
pConn->Close();
cout<<DAM<<": Cleanup Done" << endl;
}
else
{
cout<<DAM<<" : Unable to connect to data source: "<<bstrConnect<<endl;
}
::CoUninitialize();
return 0;
}
I recieve the following error when I try to build it:
fatal error C1010: unexpected end of file while looking for precompiled header. Did you forget to add #include "stdafx.h" to your source?
c:\users\lriley\documents\visual studio 2008\projects\test12\test12\test12.cpp
Any help would be appreciated.
Thanks
Dante
Well, it's been a while, but you are going to need something like: http://msdn.microsoft.com/en-us/library/ms714562%28v=vs.85%29.aspx, look at SQLConnect..., a lot of variations to a theme, but the 2nd parameter is basically the path to your access db (*.mdb) file.
good luck.
You just have to give in file properties *. Cpp
-> Precompiled Header-No Precompiled Headers
Use precompiled header file - Stdafx.h xxxx