QtBase  v6.3.1
sqldatabase_snippet.cpp
Go to the documentation of this file.
1 /****************************************************************************
2 **
3 ** Copyright (C) 2020 The Qt Company Ltd.
4 ** Contact: https://www.qt.io/licensing/
5 **
6 ** This file is part of the documentation of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:BSD$
9 ** Commercial License Usage
10 ** Licensees holding valid commercial Qt licenses may use this file in
11 ** accordance with the commercial license agreement provided with the
12 ** Software or, alternatively, in accordance with the terms contained in
13 ** a written agreement between you and The Qt Company. For licensing terms
14 ** and conditions see https://www.qt.io/terms-conditions. For further
15 ** information use the contact form at https://www.qt.io/contact-us.
16 **
17 ** BSD License Usage
18 ** Alternatively, you may use this file under the terms of the BSD license
19 ** as follows:
20 **
21 ** "Redistribution and use in source and binary forms, with or without
22 ** modification, are permitted provided that the following conditions are
23 ** met:
24 ** * Redistributions of source code must retain the above copyright
25 ** notice, this list of conditions and the following disclaimer.
26 ** * Redistributions in binary form must reproduce the above copyright
27 ** notice, this list of conditions and the following disclaimer in
28 ** the documentation and/or other materials provided with the
29 ** distribution.
30 ** * Neither the name of The Qt Company Ltd nor the names of its
31 ** contributors may be used to endorse or promote products derived
32 ** from this software without specific prior written permission.
33 **
34 **
35 ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
36 ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
37 ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
38 ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
39 ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40 ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41 ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
42 ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
43 ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
44 ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
45 ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
46 **
47 ** $QT_END_LICENSE$
48 **
49 ****************************************************************************/
50 
53  model->setQuery("SELECT name, salary FROM employee");
61  view->show();
65  }
66 
69  model.setQuery("SELECT name, salary FROM employee");
70  int salary = model.record(4).value("salary").toInt();
73 
74  {
76  int salary = model.data(model.index(4, 1)).toInt();
79  }
80 
81  for (int row = 0; row < model.rowCount(); ++row) {
82  for (int col = 0; col < model.columnCount(); ++col) {
83  qDebug() << model.data(model.index(row, col));
84  }
85  }
86 }
87 
88 class MyModel : public QSqlQueryModel
89 {
90 public:
91  QVariant data(const QModelIndex &item, int role) const override;
92  void fetchModel();
93 
95 };
96 
98 QVariant MyModel::data(const QModelIndex &item, int role) const
99 {
100  if (item.column() == m_specialColumnNo) {
101  // handle column separately
102  }
103  return QSqlQueryModel::data(item, role);
104 }
106 
108 {
111  model->setTable("employee");
112  model->setEditStrategy(QSqlTableModel::OnManualSubmit);
113  model->select();
114  model->setHeaderData(0, Qt::Horizontal, tr("Name"));
115  model->setHeaderData(1, Qt::Horizontal, tr("Salary"));
116 
117  QTableView *view = new QTableView;
118  view->setModel(model);
119  view->hideColumn(0); // don't show the ID
120  view->show();
122 
123  {
126  model.setTable("employee");
127  model.select();
128  int salary = model.record(4).value("salary").toInt();
130  }
131 }
132 
134 {
135  {
138  db.setHostName("bigblue");
139  db.setDatabaseName("flightdb");
140  db.setUserName("acarlson");
141  db.setPassword("1uTbSbAs");
142  bool ok = db.open();
144  Q_UNUSED(ok);
145  }
146 
147  {
149  QSqlDatabase firstDB = QSqlDatabase::addDatabase("QMYSQL", "first");
150  QSqlDatabase secondDB = QSqlDatabase::addDatabase("QMYSQL", "second");
152  }
153 
154  {
156  QSqlDatabase defaultDB = QSqlDatabase::database();
158  QSqlDatabase firstDB = QSqlDatabase::database("first");
160  QSqlDatabase secondDB = QSqlDatabase::database("second");
162  }
163 
164  {
165  // SELECT1
168  query.exec("SELECT name, salary FROM employee WHERE salary > 50000");
170 
172  while (query.next()) {
173  QString name = query.value(0).toString();
174  int salary = query.value(1).toInt();
175  qDebug() << name << salary;
176  }
178  }
179 
180  {
181  // FEATURE
184  int numRows;
185  query.exec("SELECT name, salary FROM employee WHERE salary > 50000");
186 
187  QSqlDatabase defaultDB = QSqlDatabase::database();
188  if (defaultDB.driver()->hasFeature(QSqlDriver::QuerySize)) {
189  numRows = query.size();
190  } else {
191  // this can be very slow
192  query.last();
193  numRows = query.at() + 1;
194  }
196  }
197 
198  {
199  // INSERT1
202  query.exec("INSERT INTO employee (id, name, salary) "
203  "VALUES (1001, 'Thad Beaumont', 65000)");
205  }
206 
207  {
208  // NAMED BINDING
211  query.prepare("INSERT INTO employee (id, name, salary) "
212  "VALUES (:id, :name, :salary)");
213  query.bindValue(":id", 1001);
214  query.bindValue(":name", "Thad Beaumont");
215  query.bindValue(":salary", 65000);
216  query.exec();
218  }
219 
220  {
221  // POSITIONAL BINDING
224  query.prepare("INSERT INTO employee (id, name, salary) "
225  "VALUES (?, ?, ?)");
226  query.addBindValue(1001);
227  query.addBindValue("Thad Beaumont");
228  query.addBindValue(65000);
229  query.exec();
231  }
232 
233  {
234  // UPDATE1
237  query.exec("UPDATE employee SET salary = 70000 WHERE id = 1003");
239  }
240 
241  {
242  // DELETE1
245  query.exec("DELETE FROM employee WHERE id = 1007");
247  }
248 
249  {
250  // TRANSACTION
254  query.exec("SELECT id FROM employee WHERE name = 'Torild Halvorsen'");
255  if (query.next()) {
256  int employeeId = query.value(0).toInt();
257  query.exec("INSERT INTO project (id, name, ownerid) "
258  "VALUES (201, 'Manhattan Project', "
259  + QString::number(employeeId) + ')');
260  }
263  }
264 
265  {
266  // SQLQUERYMODEL1
269  model.setQuery("SELECT * FROM employee");
270 
271  for (int i = 0; i < model.rowCount(); ++i) {
272  int id = model.record(i).value("id").toInt();
273  QString name = model.record(i).value("name").toString();
274  qDebug() << id << name;
275  }
277  }
278 
279  {
280  // SQLTABLEMODEL1
283  model.setTable("employee");
284  model.setFilter("salary > 50000");
285  model.setSort(2, Qt::DescendingOrder);
286  model.select();
287 
288  for (int i = 0; i < model.rowCount(); ++i) {
289  QString name = model.record(i).value("name").toString();
290  int salary = model.record(i).value("salary").toInt();
291  qDebug() << name << salary;
292  }
294  }
295 
296  {
297  // SQLTABLEMODEL2
299  model.setTable("employee");
300 
302  for (int i = 0; i < model.rowCount(); ++i) {
304  double salary = record.value("salary").toInt();
305  salary *= 1.1;
306  record.setValue("salary", salary);
307  model.setRecord(i, record);
308  }
309  model.submitAll();
311 
312  // SQLTABLEMODEL3
313  int row = 1;
314  int column = 2;
316  model.setData(model.index(row, column), 75000);
317  model.submitAll();
319 
320  // SQLTABLEMODEL4
322  model.insertRows(row, 1);
323  model.setData(model.index(row, 0), 1013);
324  model.setData(model.index(row, 1), "Peter Gordon");
325  model.setData(model.index(row, 2), 68500);
326  model.submitAll();
328 
330  model.removeRows(row, 5);
332  model.submitAll();
334  }
335 }
336 
338 class XyzResult : public QSqlResult
339 {
340 public:
342  : QSqlResult(driver) {}
344 
345 protected:
346  QVariant data(int /* index */) override { return QVariant(); }
347  bool isNull(int /* index */) override { return false; }
348  bool reset(const QString & /* query */) override { return false; }
349  bool fetch(int /* index */) override { return false; }
350  bool fetchFirst() override { return false; }
351  bool fetchLast() override { return false; }
352  int size() override { return 0; }
353  int numRowsAffected() override { return 0; }
354  QSqlRecord record() const override { return QSqlRecord(); }
355 };
357 
359 class XyzDriver : public QSqlDriver
360 {
361 public:
364 
365  bool hasFeature(DriverFeature /* feature */) const override { return false; }
366  bool open(const QString & /* db */, const QString & /* user */,
367  const QString & /* password */, const QString & /* host */,
368  int /* port */, const QString & /* options */) override
369  { return false; }
370  void close() {}
371  QSqlResult *createResult() const override { return new XyzResult(this); }
372 };
374 
375 int main(int argc, char **argv)
376 {
377  QCoreApplication app(argc, argv);
378 
384 
385  XyzDriver driver;
386  XyzResult result(&driver);
387 }
small capitals from c petite p scientific i
[1]
Definition: afcover.h:80
[Quoting ModelView Tutorial]
Definition: mymodel.h:59
void fetchModel()
QVariant data(const QModelIndex &item, int role) const override
int m_specialColumnNo
QVariant data(const QModelIndex &index, int role=Qt::DisplayRole) const override
[Quoting ModelView Tutorial]
Definition: mymodel.cpp:70
virtual bool removeRows(int row, int count, const QModelIndex &parent=QModelIndex())
virtual Q_INVOKABLE bool setData(const QModelIndex &index, const QVariant &value, int role=Qt::EditRole)
virtual bool insertRows(int row, int count, const QModelIndex &parent=QModelIndex())
void setEditTriggers(EditTriggers triggers)
QModelIndex index(int row, int column, const QModelIndex &parent=QModelIndex()) const override
The QCoreApplication class provides an event loop for Qt applications without UI.
The QModelIndex class is used to locate data in a data model.
The QSqlDatabase class handles a connection to a database.
Definition: qsqldatabase.h:71
QSqlDriver * driver() const
bool transaction()
static QSqlDatabase database(const QString &connectionName=QLatin1String(defaultConnection), bool open=true)
static QSqlDatabase addDatabase(const QString &type, const QString &connectionName=QLatin1String(defaultConnection))
The QSqlDriver class is an abstract base class for accessing specific SQL databases.
Definition: qsqldriver.h:61
virtual bool hasFeature(DriverFeature f) const =0
The QSqlQuery class provides a means of executing and manipulating SQL statements.
Definition: qsqlquery.h:59
The QSqlQueryModel class provides a read-only data model for SQL result sets.
QVariant data(const QModelIndex &item, int role=Qt::DisplayRole) const override
int rowCount(const QModelIndex &parent=QModelIndex()) const override
void setQuery(QSqlQuery &&query)
bool setHeaderData(int section, Qt::Orientation orientation, const QVariant &value, int role=Qt::EditRole) override
int columnCount(const QModelIndex &parent=QModelIndex()) const override
QSqlRecord record(int row) const
The QSqlRecord class encapsulates a database record.
Definition: qsqlrecord.h:54
QVariant value(int i) const
Definition: qsqlrecord.cpp:193
The QSqlResult class provides an abstract interface for accessing data from specific SQL databases.
Definition: qsqlresult.h:61
const QSqlDriver * driver() const
Definition: qsqlresult.cpp:366
The QSqlTableModel class provides an editable data model for a single database table.
The QString class provides a Unicode character string.
Definition: qstring.h:388
static QString number(int, int base=10)
Definition: qstring.cpp:7538
The QTableView class provides a default model/view implementation of a table view.
Definition: qtableview.h:54
void setModel(QAbstractItemModel *model) override
void hideColumn(int column)
The QVariant class acts like a union for the most common Qt data types.
Definition: qvariant.h:95
int toInt(bool *ok=nullptr) const
Definition: qvariant.cpp:1833
QString toString() const
Definition: qvariant.cpp:1416
QSqlResult * createResult() const override
bool open(const QString &, const QString &, const QString &, const QString &, int, const QString &) override
bool hasFeature(DriverFeature) const override
bool fetch(int) override
int numRowsAffected() override
QVariant data(int) override
bool fetchLast() override
bool fetchFirst() override
bool reset(const QString &) override
QSqlRecord record() const override
XyzResult(const QSqlDriver *driver)
bool isNull(int) override
int size() override
@ Horizontal
Definition: qnamespace.h:124
@ DescendingOrder
Definition: qnamespace.h:148
#define qDebug
[1]
Definition: qlogging.h:177
GLuint name
GLenum GLenum GLsizei void GLsizei void * column
Definition: qopenglext.h:2747
GLenum query
Definition: qopenglext.h:2738
GLenum GLenum GLsizei void * row
Definition: qopenglext.h:2747
GLuint64EXT * result
[6]
Definition: qopenglext.h:10932
#define tr(X)
void QSqlField_snippets()
Definition: sqldatabase.cpp:78
void QSqlDatabase_snippets()
Definition: sqldatabase.cpp:57
void QSqlQueryModel_snippets()
void QSqlQuery_snippets()
int main(int argc, char **argv)
[48]
void sql_intro_snippets()
QTableView * view
[17]
QSqlQueryModel * model
[16]
Q_UNUSED(salary)
[21]
void QSqlTableModel_snippets()
[23]
int salary
QMimeDatabase db
[0]
MyRecord record(int row) const
[0]
QGraphicsItem * item
QApplication app(argc, argv)
[0]