#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)
Related
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.
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.
hi i am getting a problem while using tntdb classes in my c++ code only integer values atr updating in database while string values are updating as garbage values i am giving my code below please help me out to solve this issue
#include <tntdb/connection.h>
#include <tntdb/connect.h>
#include <stdio.h>
#include <string>
#include <sys/shm.h>
using namespace std;
int main()
{
string s="create table test2(T1 int not null primary key,NAME varchar(20),STATUS varchar(20));";
try{
tntdb::Connection conn;
conn = tntdb::connect("sqlite:/home/gaian/Desktop/test.db");
string k="abc";
conn.execute(s);
tntdb::Statement st = conn.prepare("insert into test2(T1,NAME,STATUS) values (:T1, :NAME,:STATUS)");
st.set("T1",10)
.set("NAME",k)
.set("STATUS","bye")
.execute();
}
catch(const std::exception& e){
printf("error is %s\n",e.what());
}
return 0;
}
I run your code and it works fine on my plateform.
In order to avoid implicit cast you could use setString instead of set, that is to say :
st.set("T1",10)
.setString("NAME",k)
.setString("STATUS","bye")
.execute();
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
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" ) ) {