//qt下链接sqlite数据库。
//头文件
#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();