Qt 5.10 Book Examples
chapter41
SQL
main.cpp
Go to the documentation of this file.
1
// ======================================================================
2
// main.cpp
3
// ======================================================================
4
// This file is a part of the book
5
// "Qt 5.10 Professional programming with C++"
6
// http://qt-book.com
7
// ======================================================================
8
// Copyright (c) 2017 by Max Schlee
9
// ======================================================================
10
11
#include <QtSql>
12
13
static
bool
createConnection()
14
{
15
QSqlDatabase db = QSqlDatabase::addDatabase(
"QSQLITE"
);
16
db.setDatabaseName(
"addressbook"
);
17
18
db.setUserName(
"elton"
);
19
db.setHostName(
"epica"
);
20
db.setPassword(
"password"
);
21
if
(!db.open()) {
22
qDebug() <<
"Cannot open database:"
<< db.lastError();
23
return
false
;
24
}
25
return
true
;
26
}
27
28
// ----------------------------------------------------------------------
29
int
main
(
int
argc,
char
** argv)
30
{
31
QCoreApplication app(argc, argv);
32
33
if
(!createConnection()) {
34
return
-1;
35
}
36
37
//Creating of the data base
38
QSqlQuery query;
39
QString str =
"CREATE TABLE addressbook ( "
40
"number INTEGER PRIMARY KEY NOT NULL, "
41
"name VARCHAR(15), "
42
"phone VARCHAR(12), "
43
"email VARCHAR(15) "
44
");"
;
45
46
if
(!query.exec(str)) {
47
qDebug() <<
"Unable to create a table"
;
48
}
49
50
//Adding some information
51
QString strF =
52
"INSERT INTO addressbook (number, name, phone, email) "
53
"VALUES(%1, '%2', '%3', '%4');"
;
54
55
str = strF.arg(
"1"
)
56
.arg(
"Piggy"
)
57
.arg(
"+49 631322187"
)
58
.arg(
"piggy@mega.de"
);
59
if
(!query.exec(str)) {
60
qDebug() <<
"Unable to make insert opeation"
;
61
}
62
63
str = strF.arg(
"2"
)
64
.arg(
"Kermit"
)
65
.arg(
"+49 631322181"
)
66
.arg(
"kermit@mega.de"
);
67
if
(!query.exec(str)) {
68
qDebug() <<
"Unable to make insert operation"
;
69
}
70
71
if
(!query.exec(
"SELECT * FROM addressbook;"
)) {
72
qDebug() <<
"Unable to execute query - exiting"
;
73
return
1;
74
}
75
76
//Reading of the data
77
QSqlRecord rec = query.record();
78
int
nNumber = 0;
79
QString strName;
80
QString strPhone;
81
QString strEmail;
82
83
while
(query.next()) {
84
nNumber = query.value(rec.indexOf(
"number"
)).toInt();
85
strName = query.value(rec.indexOf(
"name"
)).toString();
86
strPhone = query.value(rec.indexOf(
"phone"
)).toString();
87
strEmail = query.value(rec.indexOf(
"email"
)).toString();
88
89
qDebug() << nNumber <<
" "
<< strName <<
";\t"
90
<< strPhone <<
";\t"
<< strEmail;
91
}
92
93
return
0;
94
}
95
main
int main(int argc, char **argv)
Definition:
main.cpp:15
Generated by
1.8.14