source: trunk/doc/src/snippets/sqldatabase/sqldatabase.cpp@ 1168

Last change on this file since 1168 was 846, checked in by Dmitry A. Kuminov, 14 years ago

trunk: Merged in qt 4.7.2 sources from branches/vendor/nokia/qt.

File size: 13.3 KB
Line 
1/****************************************************************************
2**
3** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
4** All rights reserved.
5** Contact: Nokia Corporation ([email protected])
6**
7** This file is part of the documentation of the Qt Toolkit.
8**
9** $QT_BEGIN_LICENSE:BSD$
10** You may use this file under the terms of the BSD license as follows:
11**
12** "Redistribution and use in source and binary forms, with or without
13** modification, are permitted provided that the following conditions are
14** met:
15** * Redistributions of source code must retain the above copyright
16** notice, this list of conditions and the following disclaimer.
17** * Redistributions in binary form must reproduce the above copyright
18** notice, this list of conditions and the following disclaimer in
19** the documentation and/or other materials provided with the
20** distribution.
21** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
22** the names of its contributors may be used to endorse or promote
23** products derived from this software without specific prior written
24** permission.
25**
26** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
27** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
28** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
29** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
30** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
31** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
32** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
33** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
34** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
35** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
36** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
37** $QT_END_LICENSE$
38**
39****************************************************************************/
40
41#include <QtGui>
42#include <QtSql>
43
44#include <iostream>
45
46using namespace std;
47
48QString tr(const char *text)
49{
50 return QApplication::translate(text, text);
51}
52
53void QSqlDatabase_snippets()
54{
55 {
56//! [0]
57 QSqlDatabase db = QSqlDatabase::addDatabase("QPSQL");
58 db.setHostName("acidalia");
59 db.setDatabaseName("customdb");
60 db.setUserName("mojito");
61 db.setPassword("J0a1m8");
62 bool ok = db.open();
63//! [0]
64 Q_UNUSED(ok);
65 }
66
67 {
68//! [1]
69 QSqlDatabase db = QSqlDatabase::database();
70//! [1]
71 }
72}
73
74void QSqlField_snippets()
75{
76#if 0
77 {
78//! [2]
79 QSqlField field("age", QVariant::Int);
80 field.setValue(QPixmap()); // WRONG
81//! [2]
82 }
83#endif
84
85 {
86//! [3]
87 QSqlField field("age", QVariant::Int);
88 field.setValue(QString("123")); // casts QString to int
89//! [3]
90 }
91
92 {
93//! [4]
94 QSqlQuery query;
95//! [4] //! [5]
96 QSqlRecord record = query.record();
97//! [5] //! [6]
98 QSqlField field = record.field("country");
99//! [6]
100 }
101}
102
103void doSomething(const QString &)
104{
105}
106
107void QSqlQuery_snippets()
108{
109 {
110 // typical loop
111//! [7]
112 QSqlQuery query("SELECT country FROM artist");
113 while (query.next()) {
114 QString country = query.value(0).toString();
115 doSomething(country);
116 }
117//! [7]
118 }
119
120 {
121 // field index lookup
122//! [8]
123 QSqlQuery query("SELECT * FROM artist");
124 int fieldNo = query.record().indexOf("country");
125 while (query.next()) {
126 QString country = query.value(fieldNo).toString();
127 doSomething(country);
128 }
129//! [8]
130 }
131
132 {
133 // named with named
134//! [9]
135 QSqlQuery query;
136 query.prepare("INSERT INTO person (id, forename, surname) "
137 "VALUES (:id, :forename, :surname)");
138 query.bindValue(":id", 1001);
139 query.bindValue(":forename", "Bart");
140 query.bindValue(":surname", "Simpson");
141 query.exec();
142//! [9]
143 }
144
145 {
146 // positional with named
147//! [10]
148 QSqlQuery query;
149 query.prepare("INSERT INTO person (id, forename, surname) "
150 "VALUES (:id, :forename, :surname)");
151 query.bindValue(0, 1001);
152 query.bindValue(1, "Bart");
153 query.bindValue(2, "Simpson");
154 query.exec();
155//! [10]
156 }
157
158 {
159 // positional 1
160//! [11]
161 QSqlQuery query;
162 query.prepare("INSERT INTO person (id, forename, surname) "
163 "VALUES (?, ?, ?)");
164 query.bindValue(0, 1001);
165 query.bindValue(1, "Bart");
166 query.bindValue(2, "Simpson");
167 query.exec();
168//! [11]
169 }
170
171 {
172 // positional 2
173//! [12]
174 QSqlQuery query;
175 query.prepare("INSERT INTO person (id, forename, surname) "
176 "VALUES (?, ?, ?)");
177 query.addBindValue(1001);
178 query.addBindValue("Bart");
179 query.addBindValue("Simpson");
180 query.exec();
181//! [12]
182 }
183
184 {
185 // stored
186//! [13]
187 QSqlQuery query;
188 query.prepare("CALL AsciiToInt(?, ?)");
189 query.bindValue(0, "A");
190 query.bindValue(1, 0, QSql::Out);
191 query.exec();
192 int i = query.boundValue(1).toInt(); // i is 65
193//! [13]
194 Q_UNUSED(i);
195 }
196
197 QSqlQuery query;
198
199 {
200 // examine with named binding
201//! [14]
202 QMapIterator<QString, QVariant> i(query.boundValues());
203 while (i.hasNext()) {
204 i.next();
205 cout << i.key().toAscii().data() << ": "
206 << i.value().toString().toAscii().data() << endl;
207 }
208//! [14]
209 }
210
211 {
212 // examine with positional binding
213//! [15]
214 QList<QVariant> list = query.boundValues().values();
215 for (int i = 0; i < list.size(); ++i)
216 cout << i << ": " << list.at(i).toString().toAscii().data() << endl;
217//! [15]
218 }
219}
220
221void QSqlQueryModel_snippets()
222{
223 {
224//! [16]
225 QSqlQueryModel *model = new QSqlQueryModel;
226 model->setQuery("SELECT name, salary FROM employee");
227 model->setHeaderData(0, Qt::Horizontal, tr("Name"));
228 model->setHeaderData(1, Qt::Horizontal, tr("Salary"));
229
230//! [17]
231 QTableView *view = new QTableView;
232//! [17] //! [18]
233 view->setModel(model);
234//! [18] //! [19]
235 view->show();
236//! [16] //! [19] //! [20]
237 view->setEditTriggers(QAbstractItemView::NoEditTriggers);
238//! [20]
239 }
240
241//! [21]
242 QSqlQueryModel model;
243 model.setQuery("SELECT * FROM employee");
244 int salary = model.record(4).value("salary").toInt();
245//! [21]
246 Q_UNUSED(salary);
247
248 {
249//! [22]
250 int salary = model.data(model.index(4, 2)).toInt();
251//! [22]
252 Q_UNUSED(salary);
253 }
254
255 for (int row = 0; row < model.rowCount(); ++row) {
256 for (int col = 0; col < model.columnCount(); ++col) {
257 qDebug() << model.data(model.index(row, col));
258 }
259 }
260}
261
262class MyModel : public QSqlQueryModel
263{
264public:
265 QVariant data(const QModelIndex &item, int role) const;
266
267 int m_specialColumnNo;
268};
269
270//! [23]
271QVariant MyModel::data(const QModelIndex &item, int role) const
272{
273 if (item.column() == m_specialColumnNo) {
274 // handle column separately
275 }
276 return QSqlQueryModel::data(item, role);
277}
278//! [23]
279
280void QSqlTableModel_snippets()
281{
282//! [24]
283 QSqlTableModel *model = new QSqlTableModel(parentObject, database);
284 model->setTable("employee");
285 model->setEditStrategy(QSqlTableModel::OnManualSubmit);
286 model->select();
287 model->removeColumn(0); // don't show the ID
288 model->setHeaderData(0, Qt::Horizontal, tr("Name"));
289 model->setHeaderData(1, Qt::Horizontal, tr("Salary"));
290
291 QTableView *view = new QTableView;
292 view->setModel(model);
293 view->show();
294//! [24]
295
296 {
297//! [25]
298 QSqlTableModel model;
299 model.setTable("employee");
300 QString name = model.record(4).value("name").toString();
301//! [25]
302 }
303}
304
305void sql_intro_snippets()
306{
307 {
308//! [26]
309 QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
310 db.setHostName("bigblue");
311 db.setDatabaseName("flightdb");
312 db.setUserName("acarlson");
313 db.setPassword("1uTbSbAs");
314 bool ok = db.open();
315//! [26]
316 Q_UNUSED(ok);
317 }
318
319 {
320//! [27]
321 QSqlDatabase firstDB = QSqlDatabase::addDatabase("QMYSQL", "first");
322 QSqlDatabase secondDB = QSqlDatabase::addDatabase("QMYSQL", "second");
323//! [27]
324 }
325
326 {
327//! [28]
328 QSqlDatabase defaultDB = QSqlDatabase::database();
329//! [28] //! [29]
330 QSqlDatabase firstDB = QSqlDatabase::database("first");
331//! [29] //! [30]
332 QSqlDatabase secondDB = QSqlDatabase::database("second");
333//! [30]
334 }
335
336 {
337 // SELECT1
338//! [31]
339 QSqlQuery query;
340 query.exec("SELECT name, salary FROM employee WHERE salary > 50000");
341//! [31]
342
343//! [32]
344 while (query.next()) {
345 QString name = query.value(0).toString();
346 int salary = query.value(1).toInt();
347 qDebug() << name << salary;
348 }
349//! [32]
350 }
351
352 {
353 // FEATURE
354//! [33]
355 QSqlQuery query;
356 int numRows;
357 query.exec("SELECT name, salary FROM employee WHERE salary > 50000");
358
359 QSqlDatabase defaultDB = QSqlDatabase::database();
360 if (defaultDB.driver()->hasFeature(QSqlDriver::QuerySize)) {
361 numRows = query.size();
362 } else {
363 // this can be very slow
364 query.last();
365 numRows = query.at() + 1;
366 }
367//! [33]
368 }
369
370 {
371 // INSERT1
372//! [34]
373 QSqlQuery query;
374 query.exec("INSERT INTO employee (id, name, salary) "
375 "VALUES (1001, 'Thad Beaumont', 65000)");
376//! [34]
377 }
378
379 {
380 // NAMED BINDING
381//! [35]
382 QSqlQuery query;
383 query.prepare("INSERT INTO employee (id, name, salary) "
384 "VALUES (:id, :name, :salary)");
385 query.bindValue(":id", 1001);
386 query.bindValue(":name", "Thad Beaumont");
387 query.bindValue(":salary", 65000);
388 query.exec();
389//! [35]
390 }
391
392 {
393 // POSITIONAL BINDING
394//! [36]
395 QSqlQuery query;
396 query.prepare("INSERT INTO employee (id, name, salary) "
397 "VALUES (?, ?, ?)");
398 query.addBindValue(1001);
399 query.addBindValue("Thad Beaumont");
400 query.addBindValue(65000);
401 query.exec();
402//! [36]
403 }
404
405 {
406 // UPDATE1
407//! [37]
408 QSqlQuery query;
409 query.exec("UPDATE employee SET salary = 70000 WHERE id = 1003");
410//! [37]
411 }
412
413 {
414 // DELETE1
415//! [38]
416 QSqlQuery query;
417 query.exec("DELETE FROM employee WHERE id = 1007");
418//! [38]
419 }
420
421 {
422 // TRANSACTION
423//! [39]
424 QSqlDatabase::database().transaction();
425 QSqlQuery query;
426 query.exec("SELECT id FROM employee WHERE name = 'Torild Halvorsen'");
427 if (query.next()) {
428 int employeeId = query.value(0).toInt();
429 query.exec("INSERT INTO project (id, name, ownerid) "
430 "VALUES (201, 'Manhattan Project', "
431 + QString::number(employeeId) + ')');
432 }
433 QSqlDatabase::database().commit();
434//! [39]
435 }
436
437 {
438 // SQLQUERYMODEL1
439//! [40]
440 QSqlQueryModel model;
441 model.setQuery("SELECT * FROM employee");
442
443 for (int i = 0; i < model.rowCount(); ++i) {
444 int id = model.record(i).value("id").toInt();
445 QString name = model.record(i).value("name").toString();
446 qDebug() << id << name;
447 }
448//! [40]
449 }
450
451 {
452 // SQLTABLEMODEL1
453//! [41]
454 QSqlTableModel model;
455 model.setTable("employee");
456 model.setFilter("salary > 50000");
457 model.setSort(2, Qt::DescendingOrder);
458 model.select();
459
460 for (int i = 0; i < model.rowCount(); ++i) {
461 QString name = model.record(i).value("name").toString();
462 int salary = model.record(i).value("salary").toInt();
463 qDebug() << name << salary;
464 }
465//! [41]
466 }
467
468 {
469 // SQLTABLEMODEL2
470 QSqlTableModel model;
471 model.setTable("employee");
472
473//! [42]
474 for (int i = 0; i < model.rowCount(); ++i) {
475 QSqlRecord record = model.record(i);
476 double salary = record.value("salary").toInt();
477 salary *= 1.1;
478 record.setValue("salary", salary);
479 model.setRecord(i, record);
480 }
481 model.submitAll();
482//! [42]
483
484 // SQLTABLEMODEL3
485 int row = 1;
486 int column = 2;
487//! [43]
488 model.setData(model.index(row, column), 75000);
489 model.submitAll();
490//! [43]
491
492 // SQLTABLEMODEL4
493//! [44]
494 model.insertRows(row, 1);
495 model.setData(model.index(row, 0), 1013);
496 model.setData(model.index(row, 1), "Peter Gordon");
497 model.setData(model.index(row, 2), 68500);
498 model.submitAll();
499//! [44]
500
501//! [45]
502 model.removeRows(row, 5);
503//! [45] //! [46]
504 model.submitAll();
505//! [46]
506 }
507}
508
509//! [47]
510class XyzResult : public QSqlResult
511{
512public:
513 XyzResult(const QSqlDriver *driver)
514 : QSqlResult(driver) {}
515 ~XyzResult() {}
516
517protected:
518 QVariant data(int /* index */) { return QVariant(); }
519 bool isNull(int /* index */) { return false; }
520 bool reset(const QString & /* query */) { return false; }
521 bool fetch(int /* index */) { return false; }
522 bool fetchFirst() { return false; }
523 bool fetchLast() { return false; }
524 int size() { return 0; }
525 int numRowsAffected() { return 0; }
526 QSqlRecord record() const { return QSqlRecord(); }
527};
528//! [47]
529
530//! [48]
531class XyzDriver : public QSqlDriver
532{
533public:
534 XyzDriver() {}
535 ~XyzDriver() {}
536
537 bool hasFeature(DriverFeature /* feature */) const { return false; }
538 bool open(const QString & /* db */, const QString & /* user */,
539 const QString & /* password */, const QString & /* host */,
540 int /* port */, const QString & /* options */)
541 { return false; }
542 void close() {}
543 QSqlResult *createResult() const { return new XyzResult(this); }
544};
545//! [48]
546
547int main(int argc, char **argv)
548{
549 QApplication app(argc, argv);
550
551 QSqlDatabase_snippets();
552 QSqlField_snippets();
553 QSqlQuery_snippets();
554 QSqlQueryModel_snippets();
555 QSqlTableModel_snippets();
556
557 XyzDriver driver;
558 XyzResult result(&driver);
559}
Note: See TracBrowser for help on using the repository browser.