QtableWidget实现显示MySql数据库表

1.初始化Qtablewidget

QSqlQuery query;
    int row =0;
    int columns = 0;
    //初始化行数
    QString sql = QString("select count(*) as row from student");
    query.exec(sql);
    if(query.first())
    {
        row =  query.value("row").toInt();
        ui->tableWidget->setRowCount(row);
    }
    //初始化列数(mysql中存在一个information_schema这个数据库,存放各个表的信息)
    sql = QString("select count(*)  as  columus from information_schema.COLUMNS where table_name='student'");
    query.exec(sql);
    if(query.first())
    {
        columns = query.value("columns").toInt();
        ui->tableWidget->setColumnCount(columns);//列
    }
2.设置表头

QStringList header;
//将表头写入表格
header<<“id”<<“name”<<“语文”<<“数学”<<“英语”<<“平均分”;
ui->tableWidget->setHorizontalHeaderLabels(header);
//自动调整宽度
ui->tableWidget->horizontalHeader()->setStretchLastSection(true);
3.将数据库中的数据写入表格

sql = QString("select * from student ");
    query.exec(sql);
        for(int i = 0; query.next(); i++)
        {
            for(int j = 0; j < columns; j++)
            {
                ui->tableWidget->setItem(i,j, new QTableWidgetItem(query.value(j).toString()));
            }
        }

4.插入空行

	QSqlQuery query;
    //在数据库插入空行
    QString sql = QString ("insert into student values(null, null, null,null,null,null)");
    query.exec(sql);

    //在Qtablewidget中插入空行
    int i =ui->tableWidget->rowCount();
    ui->tableWidget->insertRow(i);

5.删除一行数据

int choose = QMessageBox::question(this, "提示","是否确认删除",QMessageBox::Yes|QMessageBox::No);
    if(choose == QMessageBox::Yes)
    {
    	//在Qtablewidget中删除一行
        int row = ui->tableWidget->currentRow();
        ui->tableWidget->removeRow(row);
    }

	//在数据库中删除一行
    QSqlQuery query;
    QString sql = QString("delete  a from student  a inner join (select * from student limit %1,1)b on b.id = a.id ")
    .arg(ui->tableWidget->currentRow());
    query.exec(sql);
   

你可能感兴趣的:(QtableWidget实现显示MySql数据库表)