#include "Dialog.h"
#include "ui_Dialog.h"
#include <QMessageBox>
#include <QDebug>
#include <QFileDialog>
Dialog::Dialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog)
{
ui->setupUi(this);
}
Dialog::~Dialog()
{
delete ui;
}
bool Dialog::setAccessFile(const QString& filePath)
{
if(!connectionAccess(filePath))
{
QMessageBox::warning(this,QStringLiteral("警告"),QStringLiteral("数据库文件“%1”打开错误,请检查数据库文件正确性").arg(filePath));
return false;
}
QStringList tables = m_db.tables();
QStandardItemModel* tableModel = getTableListModel();
if(!tableModel)
{
tableModel = new QStandardItemModel(ui->listView);
ui->listView->setModel(tableModel);
}
tableModel->clear();
foreach (const QString& l, tables) {
qDebug()<<l;
qDebug()<<l.toLocal8Bit().toHex();
qDebug()<<l.toLatin1().toHex();
qDebug()<<l.toUtf8().toHex();
qDebug()<<"---------";
tableModel->appendRow(new QStandardItem(l));
}
return true;
}
bool Dialog::connectionAccess(const QString& filePath)
{
QString connID = "puremilk.access.connection-" + filePath;
m_db = QSqlDatabase::database(connID, false);
if (m_db.isValid())
{
if (m_db.isOpen())
return true;
}
else
m_db = QSqlDatabase::addDatabase("QODBC", connID);
if(m_db.isOpen())
{
m_db.close();
}
QString dsn = QStringLiteral(
"DRIVER={Microsoft Access Driver (*.mdb)};FIL={MS Access};DBQ=%1").arg(filePath);
m_db.setDatabaseName(dsn);
return m_db.open();
}
QStandardItemModel* Dialog::getTableListModel()
{
return qobject_cast<QStandardItemModel*>(ui->listView->model());
}
void Dialog::on_pushButton_clicked()
{
QString file = QFileDialog::getOpenFileName(this);
ui->lineEdit->setText(file);
setAccessFile(file);
}