Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
sqldatabase.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
3
4#include <QCoreApplication>
5#include <QtSql>
6#include <iostream>
7
8using namespace std;
9
11{
12 {
13//! [0]
14 QSqlDatabase db = QSqlDatabase::addDatabase("QPSQL");
15 db.setHostName("acidalia");
16 db.setDatabaseName("customdb");
17 db.setUserName("mojito");
18 db.setPassword("J0a1m8");
19 bool ok = db.open();
20//! [0]
21 Q_UNUSED(ok);
22 }
23
24 {
25//! [1]
26 QSqlDatabase db = QSqlDatabase::database();
27//! [1]
28 }
29}
30
32{
33#if 0
34 {
35//! [2]
36 QSqlField field("age", QMetaType::fromType<int>());
37 field.setValue(QPixmap()); // WRONG
38//! [2]
39 }
40#endif
41
42 {
43//! [3]
44 QSqlField field("age", QMetaType::fromType<int>());
45 field.setValue(QString("123")); // casts QString to int
46//! [3]
47 }
48
49 {
50//! [4]
51 QSqlQuery query;
52//! [4] //! [5]
53 QSqlRecord record = query.record();
54//! [5] //! [6]
55 QSqlField field = record.field("country");
56//! [6]
57 }
58}
59
60void doSomething(const QString &)
61{
62}
63
65{
66 {
67 // typical loop
68//! [7]
69 QSqlQuery query("SELECT country FROM artist");
70 while (query.next()) {
71 QString country = query.value(0).toString();
72 doSomething(country);
73 }
74//! [7]
75 }
76
77 {
78 // field index lookup
79//! [8]
80 QSqlQuery query("SELECT * FROM artist");
81 int fieldNo = query.record().indexOf("country");
82 while (query.next()) {
83 QString country = query.value(fieldNo).toString();
84 doSomething(country);
85 }
86//! [8]
87 }
88
89 {
90 // named with named
91//! [9]
92 QSqlQuery query;
93 query.prepare("INSERT INTO person (id, forename, surname) "
94 "VALUES (:id, :forename, :surname)");
95 query.bindValue(":id", 1001);
96 query.bindValue(":forename", "Bart");
97 query.bindValue(":surname", "Simpson");
98 query.exec();
99//! [9]
100 }
101
102 {
103 // positional with named
104//! [10]
105 QSqlQuery query;
106 query.prepare("INSERT INTO person (id, forename, surname) "
107 "VALUES (:id, :forename, :surname)");
108 query.bindValue(0, 1001);
109 query.bindValue(1, "Bart");
110 query.bindValue(2, "Simpson");
111 query.exec();
112//! [10]
113 }
114
115 {
116 // positional 1
117//! [11]
118 QSqlQuery query;
119 query.prepare("INSERT INTO person (id, forename, surname) "
120 "VALUES (?, ?, ?)");
121 query.bindValue(0, 1001);
122 query.bindValue(1, "Bart");
123 query.bindValue(2, "Simpson");
124 query.exec();
125//! [11]
126 }
127
128 {
129 // positional 2
130//! [12]
131 QSqlQuery query;
132 query.prepare("INSERT INTO person (id, forename, surname) "
133 "VALUES (?, ?, ?)");
134 query.addBindValue(1001);
135 query.addBindValue("Bart");
136 query.addBindValue("Simpson");
137 query.exec();
138//! [12]
139 }
140
141 {
142 // stored
143//! [13]
144 QSqlQuery query;
145 query.prepare("CALL AsciiToInt(?, ?)");
146 query.bindValue(0, "A");
147 query.bindValue(1, 0, QSql::Out);
148 query.exec();
149 int i = query.boundValue(1).toInt(); // i is 65
150//! [13]
151 Q_UNUSED(i);
152 }
153
154 QSqlQuery query;
155
156 {
157 // examine with named or positional binding
158//! [14]
159 const QVariantList list = query.boundValues();
160 for (qsizetype i = 0; i < list.size(); ++i)
161 qDebug() << i << ":" << list.at(i).toString();
162//! [14]
163 }
164}
165
167{
168
169//! [21]
170 QSqlQueryModel model;
171 model.setQuery("SELECT name, salary FROM employee");
172 int salary = model.record(4).value("salary").toInt();
173//! [21]
174 Q_UNUSED(salary);
175
176 {
177//! [22]
178 int salary = model.data(model.index(4, 1)).toInt();
179//! [22]
180 Q_UNUSED(salary);
181 }
182
183 for (int row = 0; row < model.rowCount(); ++row) {
184 for (int col = 0; col < model.columnCount(); ++col) {
185 qDebug() << model.data(model.index(row, col));
186 }
187 }
188}
189
190class MyModel : public QSqlQueryModel
191{
192public:
193 QVariant data(const QModelIndex &item, int role) const override;
195
197};
198
199//! [23]
200QVariant MyModel::data(const QModelIndex &item, int role) const
201{
202 if (item.column() == m_specialColumnNo) {
203 // handle column separately
204 }
205 return QSqlQueryModel::data(item, role);
206}
207//! [23]
208
210{
211 {
212//! [25]
213 QSqlTableModel model;
214 model.setTable("employee");
215 model.select();
216 int salary = model.record(4).value("salary").toInt();
217//! [25]
218 Q_UNUSED(salary);
219 }
220}
221
223{
224 {
225//! [26]
226 QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
227 db.setHostName("bigblue");
228 db.setDatabaseName("flightdb");
229 db.setUserName("acarlson");
230 db.setPassword("1uTbSbAs");
231 bool ok = db.open();
232//! [26]
233 Q_UNUSED(ok);
234 }
235
236 {
237//! [27]
238 QSqlDatabase firstDB = QSqlDatabase::addDatabase("QMYSQL", "first");
239 QSqlDatabase secondDB = QSqlDatabase::addDatabase("QMYSQL", "second");
240//! [27]
241 }
242
243 {
244//! [28]
245 QSqlDatabase defaultDB = QSqlDatabase::database();
246//! [28] //! [29]
247 QSqlDatabase firstDB = QSqlDatabase::database("first");
248//! [29] //! [30]
249 QSqlDatabase secondDB = QSqlDatabase::database("second");
250//! [30]
251 }
252
253 {
254 // SELECT1
255//! [31]
256 QSqlQuery query;
257 query.exec("SELECT name, salary FROM employee WHERE salary > 50000");
258//! [31]
259
260//! [32]
261 while (query.next()) {
262 QString name = query.value(0).toString();
263 int salary = query.value(1).toInt();
264 qDebug() << name << salary;
265 }
266//! [32]
267 }
268
269 {
270 // FEATURE
271//! [33]
272 QSqlQuery query;
273 int numRows;
274 query.exec("SELECT name, salary FROM employee WHERE salary > 50000");
275
276 QSqlDatabase defaultDB = QSqlDatabase::database();
277 if (defaultDB.driver()->hasFeature(QSqlDriver::QuerySize)) {
278 numRows = query.size();
279 } else {
280 // this can be very slow
281 query.last();
282 numRows = query.at() + 1;
283 }
284//! [33]
285 Q_UNUSED(numRows);
286 }
287
288 {
289 // INSERT1
290//! [34]
291 QSqlQuery query;
292 query.exec("INSERT INTO employee (id, name, salary) "
293 "VALUES (1001, 'Thad Beaumont', 65000)");
294//! [34]
295 }
296
297 {
298 // NAMED BINDING
299//! [35]
300 QSqlQuery query;
301 query.prepare("INSERT INTO employee (id, name, salary) "
302 "VALUES (:id, :name, :salary)");
303 query.bindValue(":id", 1001);
304 query.bindValue(":name", "Thad Beaumont");
305 query.bindValue(":salary", 65000);
306 query.exec();
307//! [35]
308 }
309
310 {
311 // POSITIONAL BINDING
312//! [36]
313 QSqlQuery query;
314 query.prepare("INSERT INTO employee (id, name, salary) "
315 "VALUES (?, ?, ?)");
316 query.addBindValue(1001);
317 query.addBindValue("Thad Beaumont");
318 query.addBindValue(65000);
319 query.exec();
320//! [36]
321 }
322
323 {
324 // UPDATE1
325//! [37]
326 QSqlQuery query;
327 query.exec("UPDATE employee SET salary = 70000 WHERE id = 1003");
328//! [37]
329 }
330
331 {
332 // DELETE1
333//! [38]
334 QSqlQuery query;
335 query.exec("DELETE FROM employee WHERE id = 1007");
336//! [38]
337 }
338
339 {
340 // TRANSACTION
341//! [39]
342 QSqlDatabase::database().transaction();
343 QSqlQuery query;
344 query.exec("SELECT id FROM employee WHERE name = 'Torild Halvorsen'");
345 if (query.next()) {
346 int employeeId = query.value(0).toInt();
347 query.exec("INSERT INTO project (id, name, ownerid) "
348 "VALUES (201, 'Manhattan Project', "
349 + QString::number(employeeId) + ')');
350 }
351 QSqlDatabase::database().commit();
352//! [39]
353 }
354
355 {
356 // SQLQUERYMODEL1
357//! [40]
358 QSqlQueryModel model;
359 model.setQuery("SELECT * FROM employee");
360
361 for (int i = 0; i < model.rowCount(); ++i) {
362 int id = model.record(i).value("id").toInt();
363 QString name = model.record(i).value("name").toString();
364 qDebug() << id << name;
365 }
366//! [40]
367 }
368
369 {
370 // SQLTABLEMODEL1
371//! [41]
372 QSqlTableModel model;
373 model.setTable("employee");
374 model.setFilter("salary > 50000");
375 model.setSort(2, Qt::DescendingOrder);
376 model.select();
377
378 for (int i = 0; i < model.rowCount(); ++i) {
379 QString name = model.record(i).value("name").toString();
380 int salary = model.record(i).value("salary").toInt();
381 qDebug() << name << salary;
382 }
383//! [41]
384 }
385
386 {
387 // SQLTABLEMODEL2
388 QSqlTableModel model;
389 model.setTable("employee");
390
391//! [42]
392 for (int i = 0; i < model.rowCount(); ++i) {
393 QSqlRecord record = model.record(i);
394 double salary = record.value("salary").toInt();
395 salary *= 1.1;
396 record.setValue("salary", salary);
397 model.setRecord(i, record);
398 }
399 model.submitAll();
400//! [42]
401
402 // SQLTABLEMODEL3
403 int row = 1;
404 int column = 2;
405//! [43]
406 model.setData(model.index(row, column), 75000);
407 model.submitAll();
408//! [43]
409
410 // SQLTABLEMODEL4
411//! [44]
412 model.insertRows(row, 1);
413 model.setData(model.index(row, 0), 1013);
414 model.setData(model.index(row, 1), "Peter Gordon");
415 model.setData(model.index(row, 2), 68500);
416 model.submitAll();
417//! [44]
418
419//! [45]
420 model.removeRows(row, 5);
421//! [45] //! [46]
422 model.submitAll();
423//! [46]
424 }
425}
426
427//! [47]
428class XyzResult : public QSqlResult
429{
430public:
431 XyzResult(const QSqlDriver *driver)
432 : QSqlResult(driver) {}
434
435protected:
436 QVariant data(int /* index */) override { return QVariant(); }
437 bool isNull(int /* index */) override { return false; }
438 bool reset(const QString & /* query */) override { return false; }
439 bool fetch(int /* index */) override { return false; }
440 bool fetchFirst() override { return false; }
441 bool fetchLast() override { return false; }
442 int size() override { return 0; }
443 int numRowsAffected() override { return 0; }
444 QSqlRecord record() const override { return QSqlRecord(); }
445};
446//! [47]
447
448//! [48]
449class XyzDriver : public QSqlDriver
450{
451public:
454
455 bool hasFeature(DriverFeature /* feature */) const override { return false; }
456 bool open(const QString & /* db */, const QString & /* user */,
457 const QString & /* password */, const QString & /* host */,
458 int /* port */, const QString & /* options */) override
459 { return false; }
460 void close() override {}
461 QSqlResult *createResult() const override { return new XyzResult(this); }
462};
463//! [48]
464
465int main(int argc, char **argv)
466{
467 QCoreApplication app(argc, argv);
468
474
475 XyzDriver driver;
476 XyzResult result(&driver);
477}
int m_specialColumnNo
QVariant data(const QModelIndex &index, int role) const override
[15]
void close() override
Derived classes must reimplement this pure virtual function in order to close the database connection...
QSqlResult * createResult() const override
Creates an empty SQL result on the database.
bool open(const QString &, const QString &, const QString &, const QString &, int, const QString &) override
Derived classes must reimplement this pure virtual function to open a database connection on database...
bool hasFeature(DriverFeature) const override
Returns true if the driver supports feature feature; otherwise returns false.
bool fetch(int) override
Positions the result to an arbitrary (zero-based) row index.
int numRowsAffected() override
Returns the number of rows affected by the last query executed, or -1 if it cannot be determined or i...
QVariant data(int) override
Returns the data for field index in the current row as a QVariant.
bool fetchLast() override
Positions the result to the last record (last row) in the result.
bool fetchFirst() override
Positions the result to the first record (row 0) in the result.
bool reset(const QString &) override
Sets the result to use the SQL statement query for subsequent data retrieval.
QSqlRecord record() const override
Returns the current record if the query is active; otherwise returns an empty QSqlRecord.
XyzResult(const QSqlDriver *driver)
bool isNull(int) override
Returns true if the field at position index in the current row is null; otherwise returns false.
int size() override
Returns the size of the SELECT result, or -1 if it cannot be determined or if the query is not a SELE...
void QSqlField_snippets()
void sql_intro_snippets()
void QSqlDatabase_snippets()
void QSqlTableModel_snippets()
[23]
void QSqlQueryModel_snippets()
void QSqlQuery_snippets()
void doSomething(const QString &)
int main(int argc, char *argv[])
[ctor_close]