Qt sqlite
程序员文章站
2022-07-28 15:49:33
MainWindow::MainWindow(QWidget *parent): QMainWindow(parent), ui(new Ui::MainWindow){ ui->setupUi(this); model = new QSqlQueryModel(this); ui->tableView->setModel(model); ui->tableView->horizontalHeader()->setSection...
MainWindow::MainWindow(QWidget *parent): QMainWindow(parent), ui(new Ui::MainWindow)
{
ui->setupUi(this);
model = new QSqlQueryModel(this);
ui->tableView->setModel(model);
ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
ui->tableView->horizontalHeader()->setStretchLastSection(true);
}
void MainWindow::on_btnOpen_clicked()
{
openSqlite("xx数据库.db","x表");
}
bool MainWindow::openSqlite(QString &dbname, QString &table)
{
QSqlDatabase db;
if(db.contains("qt_sql_default_connection")) {
db = QSqlDatabase::database("qt_sql_default_connection");
} else {
db= QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName(dbname);
if(!db.open()) return false;
char sql[512]={0};
sprintf_s(sql, sizeof(sql), "SELECT a.name as '名称' FROM %s as a WHERE ...", table.toUtf8().data());
model->setQuery(sql);
}
db.close();
return true;
}
本文地址:https://blog.csdn.net/weixin_41799721/article/details/107411609