· 8 years ago · May 23, 2018, 07:20 AM
1#include "sqlcontactmodel.h"
2
3#include <QDebug>
4#include <QSqlError>
5#include <QSqlQuery>
6
7static void createTable()
8{
9 if (QSqlDatabase::database().tables().contains(QStringLiteral("Contacts"))) {
10 // The table already exists; we don't need to do anything.
11 return;
12 }
13
14 QSqlQuery query;
15 if (!query.exec(
16 "CREATE TABLE IF NOT EXISTS 'Contacts' ("
17 " 'name' TEXT NOT NULL,"
18 " PRIMARY KEY(name)"
19 ")")) {
20 qFatal("Failed to query database: %s", qPrintable(query.lastError().text()));
21 }
22
23 query.exec("INSERT INTO Contacts VALUES('Albert Einstein')");
24 query.exec("INSERT INTO Contacts VALUES('Ernest Hemingway')");
25 query.exec("INSERT INTO Contacts VALUES('Hans Gude')");
26}
27
28SqlContactModel::SqlContactModel(QObject *parent)
29 : QSqlQueryModel(parent)
30{
31 createTable();
32
33 QSqlQuery query;
34 if (!query.exec("SELECT * FROM Contacts"))
35 qFatal("Contacts SELECT query failed: %s", qPrintable(query.lastError().text()));
36
37 setQuery(query);
38 if (lastError().isValid())
39 qFatal("Cannot set query on SqlContactModel: %s", qPrintable(lastError().text()));
40}