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.
Related
I am doing kind of password manager, when I try to delete some entry ids are placed wrong
For instance, ids are place like ...19,20,21... >> deleted 20 >> ...19,21,22...
The only way to fix it, that I found was deleting and creating back id column.
The part of deleting a column works fine, but creating it back though doesn't work.
Here is my code
#include <iostream>
#include <mysql/mysql.h>
#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(){
sql::Driver *myDriver; //connecting an SQL
sql::Connection *myConn;
sql::Statement *myStmt;
sql::ResultSet *myRes;
myDriver = get_driver_instance(); // connecting to db
myConn = myDriver->connect("localhost", "root", "password");
myConn->setSchema("passwords");
myStmt = myConn->createStatement(); // deleting id column
myRes = myStmt->executeQuery("ALTER TABLE password_table DROP id;");
myStmt = myConn->createStatement(); // creating id column, creates an error
myRes = myStmt->executeQuery("ALTER TABLE password_table ADD id INT(200) NOT NULL AUTO_INCREMENT FIRST, ADD PRIMARY KEY(id);");
return 0;
}
It should be noted that, if I do the same command in mysql itself, it will work, but not in code.
First, I thought that it's because of quotation marks, but that it did not work. Than I tried to reinstall mysql connector, but it did not work either.
The issue is that you are calling:
myRes = myStmt->executeQuery("ALTER TABLE password_table DROP id;");
for a query that doesn't produce results.
Instead, call
myStmt->execute("ALTER TABLE password_table DROP id;");
which returns bool to check if the command has results.
PS: and don't forget to add a try catch block on this code otherwise your program will crash and you never know why something is failing.
I have a C++ project running on Linux and gcc/g++ 4.8. I am using MySql database version 5.7 and MySql C++ connector API 1.1.12. I am trying to execute two insert statements (each for a different table) separated by a semicolon. I got this working for Statements but not for PreparedStatements. See code sample below:
#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>
....
sql::Driver* driver;
sql::Connection *con;
sql::Statement *stmt;
sql::ResultSet *res;
sql::ConnectOptionsMap options;
options["hostName"] = "tcp://127.0.0.1";
options["userName"] = "user";
options["password"] = "password";
options["schema"] = "test_db";
options["port"] = 3306;
options["CLIENT_MULTI_STATEMENTS"] = true;
driver = get_driver_instance();
con = driver->connect(options);
Against that setup, I tried to run either of the following options:
//option 1: works
stmt = con->createStatement();
stmt -> execute("INSERT INTO T_TEST1(TEST1) VALUES ('VALUE1');INSERT INTO T_TEST2(TEST2) VALUES ('VALUE2')");
//option 2: does not work
sql::PreparedStatement *pstmt = con->prepareStatement("INSERT INTO T_TEST1(TEST1) VALUES ('VALUE1');INSERT INTO T_TEST2(TEST2) VALUES ('VALUE2')");
pstmt->executeUpdate();
Option 1 works. Option 2 but throws the following error:
# ERR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INSERT INTO T_TEST2(TEST2) VALUES ('TEST9')' at line 1 (MySQL error code: 1064, SQLState: 42000 )
Is there any way to make option 2 work?
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.
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.
#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)