QT实现对sqlite数据库的操作

前端之家收集整理的这篇文章主要介绍了QT实现对sqlite数据库的操作前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
先看下效果图:
该程序对数据库的操作包括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() <<id;
string += id + "\n";
QString name = query.value(1).toString();
string += name + "\n";
}
qDebug() <<string;
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,"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()<<command; query.exec(command); } else { QMessageBox::information(this,"open database ok! delete error"); } ui->IdEdit->clear(); ui->NameEdit->clear(); this->on_QueryButton_clicked(); } else { QMessageBox::information(this,"open database error"); } db.close();}
原文链接:https://www.f2er.com/sqlite/201647.html

猜你在找的Sqlite相关文章