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
8void openDatabase()
9{
10//! [0]
11// WRONG
12QSqlDatabase db = QSqlDatabase::database(connectionName: "sales");
13QSqlQuery query("SELECT NAME, DOB FROM EMPLOYEES", db);
14QSqlDatabase::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
20void 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
28QSqlDatabase::removeDatabase(connectionName: "sales"); // correct
29//! [1]
30}
31
32void setmyDatabase()
33{
34//! [3]
35// ...
36QSqlDatabase db = QSqlDatabase::addDatabase(type: "QODBC");
37db.setDatabaseName("DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};FIL={MS Access};DBQ=myaccessfile.mdb");
38if (db.open()) {
39 // success!
40}
41// ...
42//! [3]
43}
44
45// ...
46// MySQL connection
47void dbConnect()
48{
49QSqlDatabase db;
50//! [4]
51db.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
52if (!db.open()) {
53 db.setConnectOptions(); // clears the connect option string
54 // ...
55}
56// ...
57// PostgreSQL connection
58db.setConnectOptions("requiressl=1"); // enable PostgreSQL SSL connections
59if (!db.open()) {
60 db.setConnectOptions(); // clear options
61 // ...
62}
63// ...
64// ODBC connection
65db.setConnectOptions("SQL_ATTR_ACCESS_MODE=SQL_MODE_READ_ONLY;SQL_ATTR_TRACE=SQL_OPT_TRACE_ON"); // set ODBC options
66if (!db.open()) {
67 db.setConnectOptions(); // don't try to set this option
68 // ...
69}
70}
71//! [4]
72
73void dbQdebug()
74{
75//! [8]
76QSqlDatabase db;
77qDebug() << db.isValid(); // Returns false
78
79db = QSqlDatabase::database(connectionName: "sales");
80qDebug() << db.isValid(); // Returns \c true if "sales" connection exists
81
82QSqlDatabase::removeDatabase(connectionName: "sales");
83qDebug() << db.isValid(); // Returns false
84//! [8]
85}
86

source code of qtbase/src/sql/doc/snippets/code/src_sql_kernel_qsqldatabase.cpp