//头文件
#include <QsqlTableModel>
#include <QTableView>
#include <QDebug>
#include <QsqlTableModel>
#include <QsqlQuery>
//为了方便显示我写在了MainWindow类中的构造函数中了
QsqlDatabase db = QsqlDatabase::addDatabase("QsqlITE");
QsqlTableModel *model = new QsqlTableModel(this);
//music.db数据库名字
db.setDatabaseName("music.db");
if(!db.open())
{
qDebug()<< "database is error";
}
else
{
qDebug()<<"database is ok";
}
QsqlQuery query(db);
bool bsuccess =
query.exec("create table info (music varchar(20) primary key)");//
query.exec("insert into info values('chenyf')");
query.exec("insert into info values('chenya')");
if(!bsuccess)
{
qDebug()<< "table is error";
}
else
{
qDebug()<<"table is ok";
}
//TableView控件并绑定定数据库 model = new QsqlTableModel(this); model->setTable("info"); model->setEditStrategy(QsqlTableModel::OnManualSubmit); model->select(); ui->tableView->setModel(model); ui->tableView->show();