не могу подключить базу данных из access в qt
QT += core gui sql
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
CONFIG += c++11
# You can make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
SOURCES += \
main.cpp \
mainwindow.cpp
HEADERS += \
mainwindow.h
FORMS += \
mainwindow.ui
# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QSqlDatabase>
#include <QSqlTableModel>
#include <QDebug>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private:
Ui::MainWindow *ui;
QSqlDatabase db;
QSqlTableModel *model;
};
#endif // MAINWINDOW_H
main.cpp
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
QSqlDatabase db = QSqlDatabase::addDatabase("QODBC"); //драйвер
db.setDatabaseName("DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};FIL={MS Access};DBQ=C:\\Users\\erohi\\Desktop\\dtbs.accdb");
if (db.open())
{
qDebug("База данных открыта");
}
else
{
qDebug("База данных закрыта");
}
model = new QSqlTableModel(this, db);
model->setTable("Report");
model->select();
ui->tableView->setModel(model);
}
MainWindow::~MainWindow()
{
delete ui;
}
Ответы (1 шт):
Автор решения: Sergey Tatarincev
→ Ссылка
Посмотрите что за ошибка возникает, от этого и пляшите..
if (db.open())
{
qDebug("База данных открыта");
}
else
{
// Для начала убедимся что драйвер QODBC присутствует в списке доступных
qDebug()<<" we have this dirvers: "<<QSqlDatabase::drivers();
// И посмотрим какая ошибка была при подключении (не забываем про #include <QSqlError>)
qDebug()<<"and we get this error: "<<db.lastError().text();
}