Reputation: 61
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.
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.
Upvotes: 0
Views: 2678
Reputation: 41776
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 ;)
Upvotes: 1