HEADERS += connect.hQT += sqlSOURCES += main.cpp
#ifndef CONNECT_H#define CONNECT_H#include <QSqlDatabase>#include <QSqlError>#include <QSqlQuery>static bool createConnection(){ QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE"); db.setDatabaseName("sqlitebook"); if (!db.open()) { qDebug() << "Cannot open database:" << db.lastError(); return false; } QSqlQuery query; query.exec( "create table DirInfo (id int primary key," "idDir int," "tag text(30)," "Value text(20)," "constraint fk_DirInfo_BookDir" "foreign key (idDir) references BookDir (idDir) on update cascade on delete cascade)" "create table BookDir (idDir int primary key," "name text(20))" "create table FileDir (name text," "idDir int," "idFile int," "constraint pkFileDir" "primary key (idDir, name)," "constraint fk_FileDir_BookDir" "foreign key (idDir) references BookDir (idDir) on update cascade on delete cascade," "constraint fk_FileDir_BookFile" "foreign key (idFile) references BookFile (idFile) on update cascade on delete cascade)" "create table Bookfile (idFile int primary key, " "format text(20)," "md5 text(100), " "mainname text(20))" "create table BookAnnot (idAnnot int primary key," "idBook int," "annotType varchar(1)," "txt text(20)," "constraint fk_BookAnnot_Book_ins" "foreign key (idBook) references Bookinsr (idBook) on update cascade on delete cascade)" "create table Bookinsr (idBook int primary key," "format text(20)," "md5 text(100)," "idFile int," "origId int," "constraint fk_Bookinsr_BookFile" "foreign key (idFile) references BookFile (idFile) on update cascade on delete cascade," "constraint fk_Bookinsr_Book" "foreign key (origId) references Book (origId) on update cascade on delete cascade)");return true;}#endif
#include <QtGui>#include <QtSql>#include "connect.h"void initializeModel(QSqlTableModel *model){ model->setTable("Book"); model->setEditStrategy(QSqlTableModel::OnManualSubmit); model->select();}int main(int argc, char *argv[]){ QApplication app(argc, argv); QLabel lbl("Database create"); lbl.show(); if (!createConnection()) return 1; QSqlTableModel model; initializeModel(&model); return app.exec();}
QSqlQuery query;if (!query.exec("create table DirInfo (id int primary key," "idDir int," "tag text(30)," "Value text(20)," "constraint fk_DirInfo_BookDir " // здесь пропущен пробел "foreign key (idDir) references BookDir (idDir) on update cascade on delete cascade)") qWarning() << query.lastError();
в файлах с расширением .h (headers) пишутся заголовки (объявления) функций и классов. Определения (тела) функций и классов пишутся в файлах с расширением cpp.