Qt MySQL - Creating New Table

RogerT

I am new to QT programming so I am trying simple MySQL operations (Connecting, Building Database, Building table ...)

I used c# till now, so here I used similar construction (i.e. I put pushButton to run code and print out messages in editText arrea)

My "Connecting" code works perfectly, so does the "Building Database" code, but I have trouble creating the table.

  1. My Working environment:
    • Win 7
    • QT Creator 3.4.1
    • Based on Qt 5.4.2
    • MySQL @ XAMPP v1.8.3

My Code:

void MainWindow::on_pushButton_2_clicked()
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");

    db.setHostName("localhost");
    db.setDatabaseName("myTestDB");
    db.setUserName("root");
    db.setPassword("");

    if(db.open())  { ui->textBox->append("Connected..."); db.close(); }
    else ui->textBox->append(db.lastError().text());

    QSqlQuery query;
    query.prepare( "CREATE TABLE IF NOT EXISTS myTable (id INTEGER UNIQUE PRIMARY KEY, firstname VARCHAR(30), lastname VARCHAR(30))" );
    if(query.exec())
    {
        ui->textBox->append("Table created");
    }
    else
    {
        ui->textBox->append("Error");
        ui->textBox->append("MySQL error:" + query.lastError().text());
        ui->textBox->append("MySQL error code:"+ QString::number(query.lastError().number()));
    }
}

When I run code I get this response:
Connected...
Error
MySQL error:
MySQL error code:-1

So MySQL error is empty, and MySQL error code is -1
I also run SQL code directly to check for query errors
Thanks for any help and suggestions.

Jens A. Koch

You close the database directly after connecting to it.

And you need to hand the db over to the query.

Change

if(db.open())  { ui->textBox->append("Connected..."); db.close(); }

QSqlQuery query;

to

if(db.open())  { ui->textBox->append("Connected..."); }

QSqlQuery query(db);

and then close the DB after the query.

It's your first question: Welcome to StackOverflow ;)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related