The QSqlDatabase class handles a connection to a database. 更多...
头: | #include <QSqlDatabase> |
CMake: |
find_package(Qt6 COMPONENTS Sql REQUIRED)
target_link_libraries(mytarget PRIVATE Qt6::Sql) |
qmake: | QT += sql |
QSqlDatabase (const QSqlDatabase & other ) | |
QSqlDatabase () | |
QSqlDatabase & | operator= (const QSqlDatabase & other ) |
~QSqlDatabase () | |
void | close () |
bool | commit () |
QString | connectOptions () const |
QString | connectionName () const |
QString | databaseName () const |
QSqlDriver * | driver () const |
QString | driverName () const |
QSqlQuery | exec (const QString & query = QString()) const |
QString | hostName () const |
bool | isOpen () const |
bool | isOpenError () const |
bool | isValid () const |
QSqlError | lastError () const |
QSql::NumericalPrecisionPolicy | numericalPrecisionPolicy () const |
bool | open () |
bool | open (const QString & user , const QString & password ) |
QString | password () const |
int | port () const |
QSqlIndex | primaryIndex (const QString & tablename ) const |
QSqlRecord | record (const QString & tablename ) const |
bool | rollback () |
void | setConnectOptions (const QString & options = QString()) |
void | setDatabaseName (const QString & name ) |
void | setHostName (const QString & host ) |
void | setNumericalPrecisionPolicy (QSql::NumericalPrecisionPolicy precisionPolicy ) |
void | setPassword (const QString & password ) |
void | setPort (int port ) |
void | setUserName (const QString & name ) |
QStringList | tables (QSql::TableType type = QSql::Tables) const |
bool | transaction () |
QString | userName () const |
QSqlDatabase | addDatabase (const QString & type , const QString & connectionName = QLatin1String(defaultConnection)) |
QSqlDatabase | addDatabase (QSqlDriver * driver , const QString & connectionName = QLatin1String(defaultConnection)) |
QSqlDatabase | cloneDatabase (const QSqlDatabase & other , const QString & connectionName ) |
QSqlDatabase | cloneDatabase (const QString & other , const QString & connectionName ) |
QStringList | connectionNames () |
bool | contains (const QString & connectionName = QLatin1String(defaultConnection)) |
QSqlDatabase | database (const QString & connectionName = QLatin1String(defaultConnection), bool open = true) |
QStringList | drivers () |
bool | isDriverAvailable (const QString & name ) |
void | registerSqlDriver (const QString & name , QSqlDriverCreatorBase * creator ) |
void | removeDatabase (const QString & connectionName ) |
QSqlDatabase (QSqlDriver * driver ) | |
QSqlDatabase (const QString & type ) |
The QSqlDatabase class provides an interface for accessing a database through a connection. An instance of QSqlDatabase represents the connection. The connection provides access to the database via one of the supported database drivers , which are derived from QSqlDriver . Alternatively, you can subclass your own database driver from QSqlDriver 。见 How to Write Your Own Database Driver 了解更多信息。
Create a connection (i.e., an instance of QSqlDatabase) by calling one of the static addDatabase () functions, where you specify the driver or type of driver to use (depending on the type of database) and a connection name. A connection is known by its own name, not by the name of the database it connects to. You can have multiple connections to one database. QSqlDatabase also supports the concept of a default connection, which is the unnamed connection. To create the default connection, don't pass the connection name argument when you call addDatabase (). Subsequently, the default connection will be assumed if you call any static member function without specifying the connection name. The following snippet shows how to create and open a default connection to a PostgreSQL database:
QSqlDatabase db = QSqlDatabase::addDatabase("QPSQL"); db.setHostName("acidalia"); db.setDatabaseName("customdb"); db.setUserName("mojito"); db.setPassword("J0a1m8"); bool ok = db.open();
Once the QSqlDatabase object has been created, set the connection parameters with setDatabaseName (), setUserName (), setPassword (), setHostName (), setPort (),和 setConnectOptions (). Then call open () to activate the physical connection to the database. The connection is not usable until you open it.
The connection defined above will be the default connection, because we didn't give a connection name to addDatabase() . Subsequently, you can get the default connection by calling database () without the connection name argument:
QSqlDatabase db = QSqlDatabase::database();
QSqlDatabase is a value class. Changes made to a database connection via one instance of QSqlDatabase will affect other instances of QSqlDatabase that represent the same connection. Use cloneDatabase () to create an independent database connection based on an existing one.
警告: It is highly recommended that you do not keep a copy of the QSqlDatabase around as a member of a class, as this will prevent the instance from being correctly cleaned up on shutdown. If you need to access an existing QSqlDatabase, it should be accessed with database (). If you chose to have a QSqlDatabase member variable, this needs to be deleted before the QCoreApplication instance is deleted, otherwise it may lead to undefined behavior.
If you create multiple database connections, specify a unique connection name for each one, when you call addDatabase ()。使用 database () with a connection name to get that connection. Use removeDatabase () with a connection name to remove a connection. QSqlDatabase outputs a warning if you try to remove a connection referenced by other QSqlDatabase objects. Use contains () to see if a given connection name is in the list of connections.
Some utility methods: | |
---|---|
tables () | returns the list of tables |
primaryIndex () | returns a table's primary index |
record () | returns meta-information about a table's fields |
transaction () | starts a transaction |
commit () | saves and completes a transaction |
rollback () | cancels a transaction |
hasFeature() | checks if a driver supports transactions |
lastError () | returns information about the last error |
drivers () | returns the names of the available SQL drivers |
isDriverAvailable () | checks if a particular driver is available |
registerSqlDriver () | registers a custom-made driver |
注意: QSqlDatabase::exec () is deprecated. Use QSqlQuery::exec () 代替。
注意: When using transactions, you must start the transaction before you create your query.
另请参阅 QSqlDriver , QSqlQuery , Qt SQL ,和 线程和 SQL 模块 .
[protected]
QSqlDatabase::
QSqlDatabase
(
QSqlDriver
*
driver
)
这是重载函数。
Creates a database connection using the given driver .
[protected]
QSqlDatabase::
QSqlDatabase
(const
QString
&
type
)
这是重载函数。
Creates a QSqlDatabase connection that uses the driver referred to by type 。若 type is not recognized, the database connection will have no functionality.
The currently available driver types are:
Driver Type | 描述 |
---|---|
QDB2 | IBM DB2 |
QIBASE | Borland InterBase Driver |
QMYSQL | MySQL Driver |
QOCI | Oracle Call Interface Driver |
QODBC | ODBC Driver (includes Microsoft SQL Server) |
QPSQL | PostgreSQL Driver |
QSQLITE | SQLite version 3 or above |
Additional third party drivers, including your own custom drivers, can be loaded dynamically.
另请参阅 SQL 数据库驱动程序 , registerSqlDriver (),和 drivers ().
创建副本为 other .
Creates an empty, invalid QSqlDatabase object. Use addDatabase (), removeDatabase (),和 database () to get valid QSqlDatabase objects.
赋值 other 到此对象。
销毁对象并释放任何分配资源。
注意: When the last connection is destroyed, the destructor implicitly calls close () to release the database connection.
另请参阅 close ().
[static]
QSqlDatabase
QSqlDatabase::
addDatabase
(const
QString
&
type
, const
QString
&
connectionName
= QLatin1String(defaultConnection))
Adds a database to the list of database connections using the driver type and the connection name connectionName . If there already exists a database connection called connectionName , that connection is removed.
The database connection is referred to by connectionName . The newly added database connection is returned.
若
type
is not available or could not be loaded,
isValid
() 返回
false
.
若 connectionName is not specified, the new connection becomes the default connection for the application, and subsequent calls to database () without the connection name argument will return the default connection. If a connectionName is provided here, use database( connectionName ) to retrieve the connection.
警告: If you add a connection with the same name as an existing connection, the new connection replaces the old one. If you call this function more than once without specifying connectionName , the default connection will be the one replaced.
Before using the connection, it must be initialized. e.g., call some or all of setDatabaseName (), setUserName (), setPassword (), setHostName (), setPort (),和 setConnectOptions (), and, finally, open ().
注意: 此函数是 thread-safe .
另请参阅 database (), removeDatabase (),和 线程和 SQL 模块 .
[static]
QSqlDatabase
QSqlDatabase::
addDatabase
(
QSqlDriver
*
driver
, const
QString
&
connectionName
= QLatin1String(defaultConnection))
This overload is useful when you want to create a database connection with a driver you instantiated yourself. It might be your own database driver, or you might just need to instantiate one of the Qt drivers yourself. If you do this, it is recommended that you include the driver code in your application. For example, you can create a PostgreSQL connection with your own QPSQL driver like this:
PGconn *con = PQconnectdb("host=server user=bart password=simpson dbname=springfield"); QPSQLDriver *drv = new QPSQLDriver(con); QSqlDatabase db = QSqlDatabase::addDatabase(drv); // becomes the new default connection QSqlQuery query; query.exec("SELECT NAME, ID FROM STAFF");
The above code sets up a PostgreSQL connection and instantiates a QPSQLDriver object. Next, addDatabase() is called to add the connection to the known connections so that it can be used by the Qt SQL classes. When a driver is instantiated with a connection handle (or set of handles), Qt assumes that you have already opened the database connection.
注意:
We assume that
qtdir
is the directory where Qt is installed. This will pull in the code that is needed to use the PostgreSQL client library and to instantiate a QPSQLDriver object, assuming that you have the PostgreSQL headers somewhere in your include search path.
Remember that you must link your application against the database client library. Make sure the client library is in your linker's search path, and add lines like these to your
.pro
文件:
unix:LIBS += -lpq win32:LIBS += libpqdll.lib
The method described works for all the supplied drivers. The only difference will be in the driver constructor arguments. Here is a table of the drivers included with Qt, their source code files, and their constructor arguments:
Driver | Class name | Constructor arguments | File to include |
---|---|---|---|
QPSQL | QPSQLDriver | PGconn *connection |
qsql_psql.cpp
|
QMYSQL | QMYSQLDriver | MYSQL *connection |
qsql_mysql.cpp
|
QOCI | QOCIDriver | OCIEnv *environment, OCISvcCtx *serviceContext |
qsql_oci.cpp
|
QODBC | QODBCDriver | SQLHANDLE environment, SQLHANDLE connection |
qsql_odbc.cpp
|
QDB2 | QDB2 | SQLHANDLE environment, SQLHANDLE connection |
qsql_db2.cpp
|
QSQLITE | QSQLiteDriver | sqlite *connection |
qsql_sqlite.cpp
|
QIBASE | QIBaseDriver | isc_db_handle connection |
qsql_ibase.cpp
|
警告: Adding a database connection with the same connection name as an existing connection, causes the existing connection to be replaced by the new one.
警告: The SQL framework takes ownership of the driver . It must not be deleted. To remove the connection, use removeDatabase ().
另请参阅 drivers ().
[static]
QSqlDatabase
QSqlDatabase::
cloneDatabase
(const
QSqlDatabase
&
other
, const
QString
&
connectionName
)
Clones the database connection other and stores it as connectionName . All the settings from the original database, e.g. databaseName (), hostName (), etc., are copied across. Does nothing if other is an invalid database. Returns the newly created database connection.
注意: The new connection has not been opened. Before using the new connection, you must call open ().
[static, since 5.13]
QSqlDatabase
QSqlDatabase::
cloneDatabase
(const
QString
&
other
, const
QString
&
connectionName
)
这是重载函数。
Clones the database connection other and stores it as connectionName . All the settings from the original database, e.g. databaseName (), hostName (), etc., are copied across. Does nothing if other is an invalid database. Returns the newly created database connection.
注意: The new connection has not been opened. Before using the new connection, you must call open ().
This overload is useful when cloning the database in another thread to the one that is used by the database represented by other .
该函数在 Qt 5.13 引入。
Closes the database connection, freeing any resources acquired, and invalidating any existing QSqlQuery objects that are used with the database.
This will also affect copies of this QSqlDatabase 对象。
另请参阅 removeDatabase ().
Commits a transaction to the database if the driver supports transactions and a
transaction
() has been started. Returns
true
if the operation succeeded. Otherwise it returns
false
.
注意:
For some databases, the commit will fail and return
false
if there is an
active query
using the database for a
SELECT
. Make the query
inactive
before doing the commit.
调用 lastError () to get information about errors.
另请参阅 QSqlQuery::isActive (), QSqlDriver::hasFeature (),和 rollback ().
Returns the connection options string used for this connection. The string may be empty.
另请参阅 setConnectOptions ().
Returns the connection name, which may be empty.
注意: The connection name is not the database name .
另请参阅 addDatabase ().
[static]
QStringList
QSqlDatabase::
connectionNames
()
Returns a list containing the names of all connections.
注意: 此函数是 thread-safe .
另请参阅 contains (), database (),和 线程和 SQL 模块 .
[static]
bool
QSqlDatabase::
contains
(const
QString
&
connectionName
= QLatin1String(defaultConnection))
返回
true
if the list of database connections contains
connectionName
;否则返回
false
.
注意: 此函数是 thread-safe .
另请参阅 connectionNames (), database (),和 线程和 SQL 模块 .
[static]
QSqlDatabase
QSqlDatabase::
database
(const
QString
&
connectionName
= QLatin1String(defaultConnection),
bool
open
= true)
Returns the database connection called connectionName . The database connection must have been previously added with addDatabase ()。若 open is true (the default) and the database connection is not already open it is opened now. If no connectionName is specified the default connection is used. If connectionName does not exist in the list of databases, an invalid connection is returned.
注意: 此函数是 thread-safe .
另请参阅 isOpen () 和 线程和 SQL 模块 .
Returns the connection's database name, which may be empty.
注意: The database name is not the connection name.
另请参阅 setDatabaseName ().
Returns the database driver used to access the database connection.
另请参阅 addDatabase () 和 drivers ().
Returns the connection's driver name.
另请参阅 addDatabase () 和 driver ().
[static]
QStringList
QSqlDatabase::
drivers
()
Returns a list of all the available database drivers.
另请参阅 registerSqlDriver ().
Executes a SQL statement on the database and returns a QSqlQuery 对象。使用 lastError () to retrieve error information. If query is empty, an empty, invalid query is returned and lastError () is not affected.
另请参阅 QSqlQuery and lastError ().
Returns the connection's host name; it may be empty.
另请参阅 setHostName ().
[static]
bool
QSqlDatabase::
isDriverAvailable
(const
QString
&
name
)
返回
true
if a driver called
name
is available; otherwise returns
false
.
另请参阅 drivers ().
返回
true
if the database connection is currently open; otherwise returns
false
.
返回
true
if there was an error opening the database connection; otherwise returns
false
. Error information can be retrieved using the
lastError
() 函数。
返回
true
若
QSqlDatabase
has a valid driver.
范例:
QSqlDatabase db; qDebug() << db.isValid(); // Returns false db = QSqlDatabase::database("sales"); qDebug() << db.isValid(); // Returns \c true if "sales" connection exists QSqlDatabase::removeDatabase("sales"); qDebug() << db.isValid(); // Returns false
Returns information about the last error that occurred on the database.
Failures that occur in conjunction with an individual query are reported by QSqlQuery::lastError ().
另请参阅 QSqlError and QSqlQuery::lastError ().
Returns the current default precision policy for the database connection.
另请参阅 QSql::NumericalPrecisionPolicy , setNumericalPrecisionPolicy (), QSqlQuery::numericalPrecisionPolicy (),和 QSqlQuery::setNumericalPrecisionPolicy ().
Opens the database connection using the current connection values. Returns
true
当成功时;否则返回
false
. Error information can be retrieved using
lastError
().
另请参阅 lastError (), setDatabaseName (), setUserName (), setPassword (), setHostName (), setPort (),和 setConnectOptions ().
这是重载函数。
Opens the database connection using the given
user
name and
password
。返回
true
当成功时;否则返回
false
. Error information can be retrieved using the
lastError
() 函数。
This function does not store the password it is given. Instead, the password is passed directly to the driver for opening the connection and it is then discarded.
另请参阅 lastError ().
Returns the connection's password. An empty string will be returned if the password was not set with setPassword (), and if the password was given in the open () call, or if no password was used.
另请参阅 setPassword ().
Returns the connection's port number. The value is undefined if the port number has not been set.
另请参阅 setPort ().
Returns the primary index for table tablename . If no primary index exists, an empty QSqlIndex 被返回。
注意: Some drivers, such as the QPSQL driver, may may require you to pass tablename in lower case if the table was not quoted when created. See the Qt SQL driver 文档编制,了解更多信息。
返回 QSqlRecord populated with the names of all the fields in the table (or view) called tablename . The order in which the fields appear in the record is undefined. If no such table (or view) exists, an empty record is returned.
注意: Some drivers, such as the QPSQL driver, may may require you to pass tablename in lower case if the table was not quoted when created. See the Qt SQL driver 文档编制,了解更多信息。
[static]
void
QSqlDatabase::
registerSqlDriver
(const
QString
&
name
,
QSqlDriverCreatorBase
*
creator
)
This function registers a new SQL driver called name , within the SQL framework. This is useful if you have a custom SQL driver and don't want to compile it as a plugin.
范例:
QSqlDatabase::registerSqlDriver("MYDRIVER", new QSqlDriverCreator<QSqlDriver>); QVERIFY(QSqlDatabase::drivers().contains("MYDRIVER")); QSqlDatabase db = QSqlDatabase::addDatabase("MYDRIVER"); QVERIFY(db.isValid());
QSqlDatabase 拥有所有权对于 creator pointer, so you mustn't delete it yourself.
另请参阅 drivers ().
[static]
void
QSqlDatabase::
removeDatabase
(const
QString
&
connectionName
)
Removes the database connection connectionName from the list of database connections.
警告: There should be no open queries on the database connection when this function is called, otherwise a resource leak will occur.
范例:
// WRONG QSqlDatabase db = QSqlDatabase::database("sales"); QSqlQuery query("SELECT NAME, DOB FROM EMPLOYEES", db); QSqlDatabase::removeDatabase("sales"); // will output a warning // "db" is now a dangling invalid database connection, // "query" contains an invalid result set
The correct way to do it:
{ QSqlDatabase db = QSqlDatabase::database("sales"); QSqlQuery query("SELECT NAME, DOB FROM EMPLOYEES", db); } // Both "db" and "query" are destroyed because they are out of scope QSqlDatabase::removeDatabase("sales"); // correct
To remove the default connection, which may have been created with a call to addDatabase () not specifying a connection name, you can retrieve the default connection name by calling connectionName () on the database returned by database (). Note that if a default database hasn't been created an invalid database will be returned.
注意: 此函数是 thread-safe .
另请参阅 database (), connectionName (),和 线程和 SQL 模块 .
Rolls back a transaction on the database, if the driver supports transactions and a
transaction
() has been started. Returns
true
if the operation succeeded. Otherwise it returns
false
.
注意:
For some databases, the rollback will fail and return
false
if there is an
active query
using the database for a
SELECT
. Make the query
inactive
before doing the rollback.
调用 lastError () to get information about errors.
另请参阅 QSqlQuery::isActive (), QSqlDriver::hasFeature (),和 commit ().
Sets database-specific options . This must be done before the connection is opened, otherwise it has no effect. Another possibility is to close the connection, call QSqlDatabase::setConnectOptions(), and open () the connection again.
The format of the options string is a semicolon separated list of option names or option=value pairs. The options depend on the database client used:
ODBC | MySQL | PostgreSQL |
---|---|---|
|
|
|
DB2 | OCI | |
|
|
|
SQLite | Interbase | |
|
|
范例:
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 if (!db.open()) { db.setConnectOptions(); // clears the connect option string // ... } // ... // PostgreSQL connection db.setConnectOptions("requiressl=1"); // enable PostgreSQL SSL connections if (!db.open()) { db.setConnectOptions(); // clear options // ... } // ... // ODBC connection db.setConnectOptions("SQL_ATTR_ACCESS_MODE=SQL_MODE_READ_ONLY;SQL_ATTR_TRACE=SQL_OPT_TRACE_ON"); // set ODBC options if (!db.open()) { db.setConnectOptions(); // don't try to set this option // ... } }
Refer to the client library documentation for more information about the different options.
另请参阅 connectOptions ().
Sets the connection's database name to name . To have effect, the database name must be set before the connection is opened . Alternatively, you can close () the connection, set the database name, and call open () again.
注意: database name is not the connection name . The connection name must be passed to addDatabase () at connection object create time.
For the QSQLITE driver, if the database name specified does not exist, then it will create the file for you unless the QSQLITE_OPEN_READONLY option is set.
Additionally,
name
can be set to
":memory:"
which will create a temporary database which is only available for the lifetime of the application.
For the QOCI (Oracle) driver, the database name is the TNS Service Name.
For the QODBC driver, the
name
can either be a DSN, a DSN filename (in which case the file must have a
.dsn
extension), or a connection string.
For example, Microsoft Access users can use the following connection string to open an
.mdb
file directly, instead of having to create a DSN entry in the ODBC manager:
// ... QSqlDatabase db = QSqlDatabase::addDatabase("QODBC"); db.setDatabaseName("DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};FIL={MS Access};DBQ=myaccessfile.mdb"); if (db.open()) { // success! } // ...
There is no default value.
另请参阅 databaseName (), setUserName (), setPassword (), setHostName (), setPort (), setConnectOptions (),和 open ().
Sets the connection's host name to host . To have effect, the host name must be set before the connection is opened . Alternatively, you can close () the connection, set the host name, and call open () again.
There is no default value.
另请参阅 hostName (), setUserName (), setPassword (), setDatabaseName (), setPort (), setConnectOptions (),和 open ().
Sets the default numerical precision policy used by queries created on this database connection to precisionPolicy .
Note: Drivers that don't support fetching numerical values with low precision will ignore the precision policy. You can use QSqlDriver::hasFeature () to find out whether a driver supports this feature.
Note: Setting the default precision policy to precisionPolicy doesn't affect any currently active queries.
另请参阅 QSql::NumericalPrecisionPolicy , numericalPrecisionPolicy (), QSqlQuery::setNumericalPrecisionPolicy (),和 QSqlQuery::numericalPrecisionPolicy ().
Sets the connection's password to password . To have effect, the password must be set before the connection is opened . Alternatively, you can close () the connection, set the password, and call open () again.
There is no default value.
警告: This function stores the password in plain text within Qt. Use the open () call that takes a password as parameter to avoid this behavior.
另请参阅 password (), setUserName (), setDatabaseName (), setHostName (), setPort (), setConnectOptions (),和 open ().
Sets the connection's port number to port . To have effect, the port number must be set before the connection is opened . Alternatively, you can close () the connection, set the port number, and call open () again..
There is no default value.
另请参阅 port (), setUserName (), setPassword (), setHostName (), setDatabaseName (), setConnectOptions (),和 open ().
Sets the connection's user name to name . To have effect, the user name must be set before the connection is opened . Alternatively, you can close () the connection, set the user name, and call open () again.
There is no default value.
另请参阅 userName (), setDatabaseName (), setPassword (), setHostName (), setPort (), setConnectOptions (),和 open ().
Returns a list of the database's tables, system tables and views, as specified by the parameter type .
另请参阅 primaryIndex () 和 record ().
Begins a transaction on the database if the driver supports transactions. Returns
true
if the operation succeeded. Otherwise it returns
false
.
另请参阅 QSqlDriver::hasFeature (), commit (),和 rollback ().
Returns the connection's user name; it may be empty.
另请参阅 setUserName ().