Qt
Internal/Contributor docs for the Qt SDK. <b>Note:</b> These are NOT official API docs; those are found <a href='https://doc.qt.io/'>here</a>.
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 {
15 db.setHostName("acidalia");
16 db.setDatabaseName("customdb");
17 db.setUserName("mojito");
18 db.setPassword("J0a1m8");
19 bool ok = db.open();
21 Q_UNUSED(ok);
22 }
23
24 {
28 }
29}
30
32{
33#if 0
34 {
36 QSqlField field("age", QMetaType::fromType<int>());
37 field.setValue(QPixmap()); // WRONG
39 }
40#endif
41
42 {
44 QSqlField field("age", QMetaType::fromType<int>());
45 field.setValue(QString("123")); // casts QString to int
47 }
48
49 {
53 QSqlRecord record = query.record();
55 QSqlField field = record.field("country");
57 }
58}
59
60void doSomething(const QString &)
61{
62}
63
65{
66 {
67 // typical loop
69 QSqlQuery query("SELECT country FROM artist");
70 while (query.next()) {
71 QString country = query.value(0).toString();
72 doSomething(country);
73 }
75 }
76
77 {
78 // field index lookup
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 }
87 }
88
89 {
90 // named with named
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();
100 }
101
102 {
103 // positional with named
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();
113 }
114
115 {
116 // positional 1
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();
126 }
127
128 {
129 // positional 2
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();
139 }
140
141 {
142 // stored
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
151 Q_UNUSED(i);
152 }
153
155
156 {
157 // examine with named or positional binding
159 const QVariantList list = query.boundValues();
160 for (qsizetype i = 0; i < list.size(); ++i)
161 qDebug() << i << ":" << list.at(i).toString();
163 }
164}
165
167{
168
171 model.setQuery("SELECT name, salary FROM employee");
172 int salary = model.record(4).value("salary").toInt();
175
176 {
178 int salary = model.data(model.index(4, 1)).toInt();
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
191{
192public:
193 QVariant data(const QModelIndex &item, int role) const override;
194 void fetchModel();
195
197};
198
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}
208
210{
211 {
214 model.setTable("employee");
215 model.select();
216 int salary = model.record(4).value("salary").toInt();
219 }
220}
221
223{
224 {
227 db.setHostName("bigblue");
228 db.setDatabaseName("flightdb");
229 db.setUserName("acarlson");
230 db.setPassword("1uTbSbAs");
231 bool ok = db.open();
233 Q_UNUSED(ok);
234 }
235
236 {
238 QSqlDatabase firstDB = QSqlDatabase::addDatabase("QMYSQL", "first");
239 QSqlDatabase secondDB = QSqlDatabase::addDatabase("QMYSQL", "second");
241 }
242
243 {
247 QSqlDatabase firstDB = QSqlDatabase::database("first");
249 QSqlDatabase secondDB = QSqlDatabase::database("second");
251 }
252
253 {
254 // SELECT1
257 query.exec("SELECT name, salary FROM employee WHERE salary > 50000");
259
261 while (query.next()) {
262 QString name = query.value(0).toString();
263 int salary = query.value(1).toInt();
264 qDebug() << name << salary;
265 }
267 }
268
269 {
270 // FEATURE
273 int numRows;
274 query.exec("SELECT name, salary FROM employee WHERE salary > 50000");
275
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 }
285 Q_UNUSED(numRows);
286 }
287
288 {
289 // INSERT1
292 query.exec("INSERT INTO employee (id, name, salary) "
293 "VALUES (1001, 'Thad Beaumont', 65000)");
295 }
296
297 {
298 // NAMED BINDING
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();
308 }
309
310 {
311 // POSITIONAL BINDING
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();
321 }
322
323 {
324 // UPDATE1
327 query.exec("UPDATE employee SET salary = 70000 WHERE id = 1003");
329 }
330
331 {
332 // DELETE1
335 query.exec("DELETE FROM employee WHERE id = 1007");
337 }
338
339 {
340 // TRANSACTION
342 QSqlDatabase::database().transaction();
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();
353 }
354
355 {
356 // SQLQUERYMODEL1
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 }
367 }
368
369 {
370 // SQLTABLEMODEL1
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 }
384 }
385
386 {
387 // SQLTABLEMODEL2
389 model.setTable("employee");
390
392 for (int i = 0; i < model.rowCount(); ++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();
401
402 // SQLTABLEMODEL3
403 int row = 1;
404 int column = 2;
406 model.setData(model.index(row, column), 75000);
407 model.submitAll();
409
410 // SQLTABLEMODEL4
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();
418
420 model.removeRows(row, 5);
422 model.submitAll();
424 }
425}
426
428class XyzResult : public QSqlResult
429{
430public:
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};
447
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};
464
465int main(int argc, char **argv)
466{
467 QCoreApplication app(argc, argv);
468
474
475 XyzDriver driver;
476 XyzResult result(&driver);
477}
QVariant data(const QModelIndex &item, int role) const override
[15]
int m_specialColumnNo
virtual Q_INVOKABLE bool setData(const QModelIndex &index, const QVariant &value, int role=Qt::EditRole)
Sets the role data for the item at index to value.
QModelIndex index(int row, int column, const QModelIndex &parent=QModelIndex()) const override
Returns the index of the data in row and column with parent.
\inmodule QtCore
qsizetype size() const noexcept
Definition qlist.h:397
const_reference at(qsizetype i) const noexcept
Definition qlist.h:446
\inmodule QtCore
Returns a copy of the pixmap that is transformed using the given transformation transform and transfo...
Definition qpixmap.h:27
The QSqlDatabase class handles a connection to a database.
static QSqlDatabase addDatabase(const QString &type, const QString &connectionName=QLatin1StringView(defaultConnection))
\threadsafe
static QSqlDatabase database(const QString &connectionName=QLatin1StringView(defaultConnection), bool open=true)
\threadsafe
The QSqlDriver class is an abstract base class for accessing specific SQL databases.
Definition qsqldriver.h:26
DriverFeature
This enum contains a list of features a driver might support.
Definition qsqldriver.h:33
The QSqlField class manipulates the fields in SQL database tables and views.
Definition qsqlfield.h:19
void setValue(const QVariant &value)
Sets \l value to value.
The QSqlQueryModel class provides a read-only data model for SQL result sets.
QVariant data(const QModelIndex &item, int role=Qt::DisplayRole) const override
Returns the value for the specified item and role.
int rowCount(const QModelIndex &parent=QModelIndex()) const override
If the database supports returning the size of a query (see QSqlDriver::hasFeature()),...
void setQuery(QSqlQuery &&query)
Resets the model and sets the data provider to be the given query.
int columnCount(const QModelIndex &parent=QModelIndex()) const override
\reimp
QSqlRecord record(int row) const
Returns the record containing information about the fields of the current query.
The QSqlQuery class provides a means of executing and manipulating SQL statements.
Definition qsqlquery.h:24
bool prepare(const QString &query)
Prepares the SQL query query for execution.
bool exec(const QString &query)
Executes the SQL in query.
The QSqlRecord class encapsulates a database record.
Definition qsqlrecord.h:20
QVariant value(int i) const
Returns the value of the field located at position index in the record.
The QSqlResult class provides an abstract interface for accessing data from specific SQL databases.
Definition qsqlresult.h:22
const QSqlDriver * driver() const
Returns the driver associated with the result.
The QSqlTableModel class provides an editable data model for a single database table.
\macro QT_RESTRICTED_CAST_FROM_ASCII
Definition qstring.h:129
int toInt(bool *ok=nullptr, int base=10) const
Returns the string converted to an int using base base, which is 10 by default and must be between 2 ...
Definition qstring.h:731
static QString number(int, int base=10)
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition qstring.cpp:8084
\inmodule QtCore
Definition qvariant.h:65
int toInt(bool *ok=nullptr) const
Returns the variant as an int if the variant has userType() \l QMetaType::Int, \l QMetaType::Bool,...
QString toString() const
Returns the variant as a QString if the variant has a userType() including, but not limited to:
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...
int main()
[0]
myCustomObject doSomething()
@ DescendingOrder
Definition qnamespace.h:123
#define qDebug
[1]
Definition qlogging.h:164
GLint GLsizei GLsizei GLenum GLenum GLsizei void * data
GLuint name
GLenum GLenum GLsizei void GLsizei void * column
GLenum query
GLenum GLenum GLsizei void * row
GLuint64EXT * result
[6]
#define Q_UNUSED(x)
ptrdiff_t qsizetype
Definition qtypes.h:165
void QSqlField_snippets()
void sql_intro_snippets()
void QSqlDatabase_snippets()
void QSqlTableModel_snippets()
[23]
void QSqlQueryModel_snippets()
void QSqlQuery_snippets()
QSqlQueryModel * model
[16]
QList< int > list
[14]
QMimeDatabase db
[0]
MyRecord record(int row) const
[0]
QGraphicsItem * item
QApplication app(argc, argv)
[0]