数据库删除操作
//删除操作的槽
void Widget::on_delbt_clicked()
{
QString sql;
if(ui->idedit->text()==NULL)
{
sql = "drop Stu";
}
else
{
sql = QString("delete from Stu where id = %1").arg(ui->idedit->text());
}
QSqlQuery query;
if(!query.exec(sql))
{
QMessageBox::information(this,"提示","删除失败");
}else
{
QMessageBox::information(this,"提示","删除成功");
}
}
数据库查找操作
void Widget::on_updatebt_clicked()
{
QString sql;
//获取ui界面信息
int ui_id = ui->idedit->text().toInt();
QString ui_name = ui->nameedit->text();
QString ui_sex = ui->sexedit->text();
double ui_score = ui->scoreedit->text().toDouble();
//判断要更新的数据
if(ui_name!=NULL&&ui_sex!=NULL&&ui_score!=NULL)
{
sql = QString("update Stu set name = '%1',sex = '%2',score = %3 where id = %4").
arg(ui->nameedit->text()).arg(ui->sexedit->text()).arg(ui->scoreedit->text()).arg(ui->idedit->text());
}
else if(ui_name!=NULL)
{
if(ui_sex!=NULL)
{
sql = QString("update Stu set name = '%1',sex = '%2' where id = %3").
arg(ui->nameedit->text()).arg(ui->sexedit->text()).arg(ui->idedit->text());
}
else if(ui_score!=NULL)
{
sql = QString("update Stu set name = '%1',score = %2 where id = %3").
arg(ui->nameedit->text()).arg(ui->scoreedit->text()).arg(ui->idedit->text());
}
else if(ui_sex==NULL&&ui_score==NULL)
{
sql = QString("update Stu set name = '%1' where id = %2").
arg(ui->nameedit->text()).arg(ui->idedit->text());
}
}
else if(ui_name==NULL)
{
if(ui_sex!=NULL&&ui_score!=NULL)
sql = QString("update Stu set sex = '%1',score = %2 where id = %3").
arg(ui->sexedit->text()).arg(ui->scoreedit->text()).arg(ui->idedit->text());
else if(ui_sex==NULL)
{
sql = QString("update Stu set score = '%1' where id = %2").
arg(ui->scoreedit->text()).arg(ui->idedit->text());
}
else if(ui_score==NULL)
{
sql = QString("update Stu set score = '%1',score = %2 where id = %3").
arg(ui->scoreedit->text()).arg(ui->idedit->text());
}
}
else if(ui_id==NULL)
{
QMessageBox::information(this,"提示","请输入id");
}
//准备sql语句
QSqlQuery query;
if(!query.exec(sql))
{
QMessageBox::information(this,"提示","更新失败");
}else
{
QMessageBox::information(this,"提示","更新成功");
}
}