简体   繁体   English

Qt MySQL-创建新表

[英]Qt MySQL - Creating New Table

I am new to QT programming so I am trying simple MySQL operations (Connecting, Building Database, Building table ...) 我是QT编程的新手,所以我正在尝试简单的MySQL操作(连接,构建数据库,构建表...)

I used c# till now, so here I used similar construction (ie I put pushButton to run code and print out messages in editText arrea) 到目前为止,我一直使用c#,所以在这里我使用了类似的构造(即,我使用pushButton来运行代码并在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 赢7
    • QT Creator 3.4.1 QT Creator 3.4.1
    • Based on Qt 5.4.2 基于Qt 5.4.2
    • MySQL @ XAMPP v1.8.3 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错误:
MySQL error code:-1 MySQL错误代码:-1

So MySQL error is empty, and MySQL error code is -1 所以MySQL错误为空,而MySQL错误代码为-1
I also run SQL code directly to check for query errors 我也直接运行SQL代码以检查查询错误
Thanks for any help and suggestions. 感谢您的帮助和建议。

You close the database directly after connecting to it. 连接到数据库后,直接关闭数据库。

And you need to hand the db over to the query. 并且您需要将db移交给查询。

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 ;) 这是您的第一个问题:欢迎使用StackOverflow;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM