1 | // Copyright (C) 2016 The Qt Company Ltd. |
2 | // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause |
3 | #include <QSqlDatabase> |
4 | #include <QSqlQuery> |
5 | #include <QSqlDriver> |
6 | #include <QDebug> |
7 | |
8 | void openDatabase() |
9 | { |
10 | //! [0] |
11 | // WRONG |
12 | QSqlDatabase db = QSqlDatabase::database(connectionName: "sales" ); |
13 | QSqlQuery query("SELECT NAME, DOB FROM EMPLOYEES" , db); |
14 | QSqlDatabase::removeDatabase(connectionName: "sales" ); // will output a warning |
15 | // "db" is now a dangling invalid database connection, |
16 | // "query" contains an invalid result set |
17 | //! [0] |
18 | } |
19 | |
20 | void removeDatabase() |
21 | { |
22 | //! [1] |
23 | { |
24 | QSqlDatabase db = QSqlDatabase::database(connectionName: "sales" ); |
25 | QSqlQuery query("SELECT NAME, DOB FROM EMPLOYEES" , db); |
26 | } |
27 | // Both "db" and "query" are destroyed because they are out of scope |
28 | QSqlDatabase::removeDatabase(connectionName: "sales" ); // correct |
29 | //! [1] |
30 | } |
31 | |
32 | void setmyDatabase() |
33 | { |
34 | //! [3] |
35 | // ... |
36 | QSqlDatabase db = QSqlDatabase::addDatabase(type: "QODBC" ); |
37 | db.setDatabaseName("DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};FIL={MS Access};DBQ=myaccessfile.mdb" ); |
38 | if (db.open()) { |
39 | // success! |
40 | } |
41 | // ... |
42 | //! [3] |
43 | } |
44 | |
45 | // ... |
46 | // MySQL connection |
47 | void dbConnect() |
48 | { |
49 | QSqlDatabase db; |
50 | //! [4] |
51 | db.setConnectOptions("SSL_KEY=client-key.pem;SSL_CERT=client-cert.pem;SSL_CA=ca-cert.pem;CLIENT_IGNORE_SPACE=1" ); // use an SSL connection to the server |
52 | if (!db.open()) { |
53 | db.setConnectOptions(); // clears the connect option string |
54 | // ... |
55 | } |
56 | // ... |
57 | // PostgreSQL connection |
58 | db.setConnectOptions("requiressl=1" ); // enable PostgreSQL SSL connections |
59 | if (!db.open()) { |
60 | db.setConnectOptions(); // clear options |
61 | // ... |
62 | } |
63 | // ... |
64 | // ODBC connection |
65 | db.setConnectOptions("SQL_ATTR_ACCESS_MODE=SQL_MODE_READ_ONLY;SQL_ATTR_TRACE=SQL_OPT_TRACE_ON" ); // set ODBC options |
66 | if (!db.open()) { |
67 | db.setConnectOptions(); // don't try to set this option |
68 | // ... |
69 | } |
70 | } |
71 | //! [4] |
72 | |
73 | void dbQdebug() |
74 | { |
75 | //! [8] |
76 | QSqlDatabase db; |
77 | qDebug() << db.isValid(); // Returns false |
78 | |
79 | db = QSqlDatabase::database(connectionName: "sales" ); |
80 | qDebug() << db.isValid(); // Returns \c true if "sales" connection exists |
81 | |
82 | QSqlDatabase::removeDatabase(connectionName: "sales" ); |
83 | qDebug() << db.isValid(); // Returns false |
84 | //! [8] |
85 | } |
86 | |