Mysql c++ connector, cannot create column by code - c++

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.

Related

Multiple inserts using a single preparedStatement in a c++/mysql project

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?

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.

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.

how to use tntdb classes to update string values in Sqlite database

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();

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.