现在的位置: 首页 > 自动控制 > 工业·编程 > 正文

Qt实现对sqlite数据库的操作

2015-06-26 20:20 工业·编程 ⁄ 共 2170字 ⁄ 字号 暂无评论

本文对数据库的操作包括4个字段:ID、Name、Addr、Nick  (注意第一个字段必须是整数)

query、insert、delete按钮分别表示查询、插入、删除功能

查询按钮的实现:

void database::on_QueryButton_clicked()
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("test.db");
    bool ok = db.open();
    if (ok == true)
    {
        QSqlQuery query;
        query.exec("SELECT * from info");
        QString string;
        while (query.next())
        {
            QString id = query.value(0).toString();
            qDebug() <
            string += id + "\n";
            QString name = query.value(1).toString();
            string += name + "\n";
        }
        qDebug() <
        ui->TextEdit->setText(string);
    }
    else
    {
        QMessageBox::information(this, "ERROR", "open database error");
    }
    db.close();
}

插入按钮的实现:

void database::on_InsertButton_clicked()
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("test.db");
    bool ok = db.open();
    if (ok == true)
    {
        QSqlQuery query;
        query.prepare("INSERT INTO info (id, name) "
                  "VALUES (:id, :name)");
        query.bindValue(":id", ui->IdEdit->text().toInt());
        query.bindValue(":name", ui->NameEdit->text());
        query.exec();
        ui->IdEdit->clear();
        ui->NameEdit->clear();
        this->on_QueryButton_clicked();
    }
    else
    {
        QMessageBox::information(this, "ERROR", "open database error");
    }
    db.close();
}

删除按钮的实现:

void database::on_DeleteButton_clicked()
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("test.db");
    bool ok = db.open();
    if (ok == true)
    {
        QSqlQuery query;
        QString command="DELETE FROM info WHERE ";
        if (ui->IdEdit->text().isEmpty() == false)
        {
            command.append("id="+ui->IdEdit->text());
            query.exec(command);
        }
        else if (ui->NameEdit->text().isEmpty() == false)
        {
            command +="name=\'" + ui->NameEdit->text() + "\'";
            qDebug()<
            query.exec(command);
        }
        else
        {
            QMessageBox::information(this, "ERROR", "open database ok! delete error");
        }
        ui->IdEdit->clear();
        ui->NameEdit->clear();
        this->on_QueryButton_clicked();
    }
    else
    {
        QMessageBox::information(this, "ERROR", "open database error");
    }
    db.close();
}

给我留言

留言无头像?