Chinaunix首页 | 论坛 | 博客
  • 博客访问: 862847
  • 博文数量: 156
  • 博客积分: 6553
  • 博客等级: 准将
  • 技术积分: 3965
  • 用 户 组: 普通用户
  • 注册时间: 2010-06-22 18:36
文章存档

2012年(3)

2011年(43)

2010年(110)

分类:

2010-10-04 19:01:34

先看下效果图:
该程序对数据库的操作包括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();
}
阅读(9018) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~