C++ (Qt)MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow){ ui->setupUi(this); createConnection(); m=new QSqlQueryModel(); ui->tableView->setModel(m); refresh(); connect(ui->pushButton,SIGNAL(clicked()),this,SLOT(slotAdd())); connect(ui->pushButton_2,SIGNAL(clicked()),this,SLOT(slotRefr()));} MainWindow::~MainWindow(){ delete ui;}bool MainWindow::createConnection(){ QDir dir("data"); QString fileName = dir.absolutePath().replace("/","\\") + "\\accounts.mdb"; db = QSqlDatabase::addDatabase("QODBC"); db.setDatabaseName("DRIVER={Microsoft Access Driver (*.mdb)};FIL={MS Access};DBQ=" + fileName); if(!db.open()) { QMessageBox::critical(this,tr("Ошибка"),tr(db.lastError().text()); return false; } return true;}void MainWindow::slotRefr(){ refresh();}void MainWindow::refresh(){ QSqlDatabase db = QSqlDatabase::database(); m->setQuery("Select * from [Account]",db); ui->tableView->setCurrentIndex(m->index(0,0));} bool MainWindow::add(){ QSqlDatabase db = QSqlDatabase::database(); { QSqlDatabase dbase = QSqlDatabase::cloneDatabase(db,"other"); if(!dbase.open()) { QMessageBox::critical(this,tr("Ошибка"),tr(dbase.lastError().text()); return false; } QSqlQuery q=QSqlQuery(dbase); q.exec("INSERT INTO [Account](Num,Dat,Year) " " Values( 123455, " " 1, " " #22/03/2010#, " " 2010 )"); if(q.lastError().isValid()){ QMessageBox::information(this,"",q.lastError().text()); return false; } dbase.close(); } QSqlDatabase::removeDatabase("other"); return true;}void MainWindow::slotAdd(){ if(add()){ refresh(); QMessageBox::information(this,"","Добавилось"); }}
C++ (Qt)QSqlDatabase dbase = QSqlDatabase(db);