思维导图

QT-Day5-LMLPHP

#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    if(!db.contains("stuInfo.db"))
    {
        //说明数据库不存在
        db = QSqlDatabase::addDatabase("QSQLITE");//创建一个数据库驱动为sqlite3
        //给刚创建的数据库设置名称
        db.setDatabaseName("stuInfo.db");
    }

    if(!db.open())
    {
        QMessageBox::information(this,"","数据库打开失败");
        return;
    }
    QSqlQuery query;

    QString sql = "create table if not exists stu_info_table("
                  "id integer primary key autoincrement,"
                  "numb integer ,"
                  "name varchar(20),"
                  "sex varchar(4),"
                  "score integer)";

    //执行sql语句
    if(query.exec(sql))
    {
        QMessageBox::information(this,"","创建数据库表成功");
    }
    else {
        QMessageBox::information(this,"","数据库表创建失败");
    }


}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_addBtn_clicked()
{
    if(ui->id_edit->text().isEmpty()||
            ui->name_deit->text().isEmpty()||
            ui->sex_edit->text().isEmpty()||
            ui->score_edit->text().isEmpty())
    {
        QMessageBox::information(this,"","输入不合法");
    }
    else {
        QSqlQuery query(db); // 使用类成员变量db作为数据库连接
        QString sql = "INSERT INTO stu_info_table (numb, name, sex, score) "
                     "VALUES (:numb, :name, :sex, :score)";
        query.prepare(sql);

        query.bindValue(":numb", ui->id_edit->text().toInt());
        query.bindValue(":name", ui->name_deit->text());
        query.bindValue(":sex", ui->sex_edit->text());
        query.bindValue(":score", ui->score_edit->text().toInt());
        if(query.exec())
        {
            QMessageBox::information(this,"","插入数据成功");
        }
        else {
            QMessageBox::information(this,"","插入数据失败");
        }
    }
}

02-29 05:06