先看下效果图:
查询按钮的实现:
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();
}
{
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();
}
{
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