Home > Net >  Mysql c connector, cannot create column by code
Mysql c connector, cannot create column by code

Time:01-28

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.

CodePudding user response:

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