PySide6.QtSql.QSqlDatabase¶
- class QSqlDatabase¶
The
QSqlDatabase
class handles a connection to a database. More…Synopsis¶
Properties¶
Methods¶
def
__init__()
def
close()
def
commit()
def
connectOptions()
def
connectionName()
def
databaseName()
def
driver()
def
driverName()
def
exec()
def
exec_()
def
hostName()
def
isOpen()
def
isOpenError()
def
isValid()
def
lastError()
def
moveToThread()
def
open()
def
password()
def
port()
def
primaryIndex()
def
record()
def
rollback()
def
setHostName()
def
setPassword()
def
setPort()
def
setUserName()
def
tables()
def
thread()
def
transaction()
def
userName()
Static functions¶
def
addDatabase()
def
cloneDatabase()
def
contains()
def
database()
def
drivers()
def
removeDatabase()
Note
This documentation may contain snippets that were automatically translated from C++ to Python. We always welcome contributions to the snippet translation. If you see an issue with the translation, you can also let us know by creating a ticket on https:/bugreports.qt.io/projects/PYSIDE
Detailed Description¶
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
The
QSqlDatabase
class provides an interface for accessing a database through a connection. An instance ofQSqlDatabase
represents the connection. The connection provides access to the database via one of the supported database drivers , which are derived fromQSqlDriver
. Alternatively, you can subclass your own database driver fromQSqlDriver
. See How to Write Your Own Database Driver for more information. AQSqlDatabase
instance must only be accessed by the thread it was created in. Therefore you have to make sure to create them in the correct context. Alternatively you can change the context withmoveToThread()
.Create a connection (i.e., an instance of
QSqlDatabase
) by calling one of the staticaddDatabase()
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 calladdDatabase()
. 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:db = QSqlDatabase.addDatabase("QPSQL") db.setHostName("acidalia") db.setDatabaseName("customdb") db.setUserName("mojito") db.setPassword("J0a1m8") ok = db.open()
Once the
QSqlDatabase
object has been created, set the connection parameters withsetDatabaseName()
,setUserName()
,setPassword()
,setHostName()
,setPort()
, andsetConnectOptions()
. Then callopen()
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 callingdatabase()
without the connection name argument:db = QSqlDatabase.database()
QSqlDatabase
is a value class. Changes made to a database connection via one instance ofQSqlDatabase
will affect other instances ofQSqlDatabase
that represent the same connection. UsecloneDatabase()
to create an independent database connection based on an existing one.Warning
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 existingQSqlDatabase
, it should be accessed withdatabase()
. If you chose to have aQSqlDatabase
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()
. Usedatabase()
with a connection name to get that connection. UseremoveDatabase()
with a connection name to remove a connection.QSqlDatabase
outputs a warning if you try to remove a connection referenced by otherQSqlDatabase
objects. Usecontains()
to see if a given connection name is in the list of connections.Some utility methods:
returns the list of tables
returns a table’s primary index
returns meta-information about a table’s fields
starts a transaction
saves and completes a transaction
cancels a transaction
hasFeature()
checks if a driver supports transactions
returns information about the last error
returns the names of the available SQL drivers
checks if a particular driver is available
registers a custom-made driver
Note
When using transactions, you must start the transaction before you create your query.
See also
QSqlDriver
QSqlQuery
Qt SQLThreads and the SQL Module
Note
Properties can be used directly when
from __feature__ import true_property
is used or via accessor functions otherwise.- property numericalPrecisionPolicyᅟ: QSql.NumericalPrecisionPolicy¶
This property holds the default numerical precision policy used by queries created on this database connection.
Note: Drivers that don’t support fetching numerical values with low precision will ignore the precision policy. You can use
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.- Access functions:
- PySide6.QtSql.QSqlDatabase.defaultConnection¶
- __init__()¶
Creates an empty, invalid
QSqlDatabase
object. UseaddDatabase()
,removeDatabase()
, anddatabase()
to get validQSqlDatabase
objects.- __init__(driver)
- Parameters:
driver –
QSqlDriver
This is an overloaded function.
Creates a database connection using the given
driver
.- __init__(other)
- Parameters:
other –
QSqlDatabase
Creates a copy of
other
.- __init__(type)
- Parameters:
type – str
This is an overloaded function.
Creates a
QSqlDatabase
connection that uses the driver referred to bytype
. If thetype
is not recognized, the database connection will have no functionality.The currently available driver types are:
Driver Type
Description
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
QMIMER
Mimer SQL 11 or above
Additional third party drivers, including your own custom drivers, can be loaded dynamically.
- static addDatabase(driver[, connectionName=QLatin1StringView(QSqlDatabase.defaultConnection)])¶
- Parameters:
driver –
QSqlDriver
connectionName – str
- Return type:
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
This is an overloaded function.
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:con = PQconnectdb("host=server user=bart password=simpson dbname=springfield") drv = QPSQLDriver(con) db = QSqlDatabase.addDatabase(drv) # becomes the default() connection() query = QSqlQuery() 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.Note
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
file: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
QMIMER
QMimerSQLDriver
MimerSession *connection
qsql_mimer.cpp
QIBASE
QIBaseDriver
isc_db_handle connection
qsql_ibase.cpp
Warning
Adding a database connection with the same connection name as an existing connection, causes the existing connection to be replaced by the new one.
Warning
The SQL framework takes ownership of the
driver
. It must not be deleted. To remove the connection, useremoveDatabase()
.See also
- static addDatabase(type[, connectionName=QLatin1StringView(QSqlDatabase.defaultConnection)])
- Parameters:
type – str
connectionName – str
- Return type:
Adds a database to the list of database connections using the driver
type
and the connection nameconnectionName
. If there already exists a database connection calledconnectionName
, that connection is removed.The database connection is referred to by
connectionName
. The newly added database connection is returned.If
type
is not available or could not be loaded,isValid()
returnsfalse
.If
connectionName
is not specified, the new connection becomes the default connection for the application, and subsequent calls todatabase()
without the connection name argument will return the default connection. If aconnectionName
is provided here, use database(connectionName
) to retrieve the connection.Warning
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()
, andsetConnectOptions()
, and, finally,open()
.See also
database()
removeDatabase()
Threads and the SQL Module
- static cloneDatabase(other, connectionName)¶
- Parameters:
other –
QSqlDatabase
connectionName – str
- Return type:
Clones the database connection
other
and stores it asconnectionName
. All the settings from the original database, e.g.databaseName()
,hostName()
, etc., are copied across. Does nothing ifother
is an invalid database. Returns the newly created database connection.Note
The new connection has not been opened. Before using the new connection, you must call
open()
.- static cloneDatabase(other, connectionName)
- Parameters:
other – str
connectionName – str
- Return type:
This is an overloaded function.
Clones the database connection
other
and stores it asconnectionName
. All the settings from the original database, e.g.databaseName()
,hostName()
, etc., are copied across. Does nothing ifother
is an invalid database. Returns the newly created database connection.Note
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
.- close()¶
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
object.See also
- commit()¶
- Return type:
bool
Commits a transaction to the database if the driver supports transactions and a
transaction()
has been started. Returnstrue
if the operation succeeded. Otherwise it returnsfalse
.Note
For some databases, the commit will fail and return
false
if there is anactive query
using the database for aSELECT
. Make the queryinactive
before doing the commit.Call
lastError()
to get information about errors.See also
- connectOptions()¶
- Return type:
str
Returns the connection options string used for this connection. The string may be empty.
See also
- connectionName()¶
- Return type:
str
Returns the connection name, which may be empty.
- static connectionNames()¶
- Return type:
list of strings
Returns a list containing the names of all connections.
See also
contains()
database()
Threads and the SQL Module
- static contains([connectionName=QLatin1StringView(QSqlDatabase.defaultConnection)])¶
- Parameters:
connectionName – str
- Return type:
bool
Returns
true
if the list of database connections containsconnectionName
; otherwise returnsfalse
.See also
connectionNames()
database()
Threads and the SQL Module
- static database([connectionName=QLatin1StringView(QSqlDatabase.defaultConnection)[, open=true]])¶
- Parameters:
connectionName – str
open – bool
- Return type:
Returns the database connection called
connectionName
. The database connection must have been previously added withaddDatabase()
. Ifopen
is true (the default) and the database connection is not already open it is opened now. If noconnectionName
is specified the default connection is used. IfconnectionName
does not exist in the list of databases, an invalid connection is returned.See also
isOpen()
Threads and the SQL Module
- databaseName()¶
- Return type:
str
Returns the connection’s database name, which may be empty.
- driver()¶
- Return type:
Returns the database driver used to access the database connection.
See also
- driverName()¶
- Return type:
str
Returns the connection’s driver name.
See also
- static drivers()¶
- Return type:
list of strings
Returns a list of all the available database drivers.
See also
Executes a SQL statement on the database and returns a
QSqlQuery
object. UselastError()
to retrieve error information. Ifquery
is empty, an empty, invalid query is returned andlastError()
is not affected.Use
exec()
instead.See also
- hostName()¶
- Return type:
str
Returns the connection’s host name; it may be empty.
See also
- static isDriverAvailable(name)¶
- Parameters:
name – str
- Return type:
bool
Returns
true
if a driver calledname
is available; otherwise returnsfalse
.See also
- isOpen()¶
- Return type:
bool
Returns
true
if the database connection is currently open; otherwise returnsfalse
.- isOpenError()¶
- Return type:
bool
Returns
true
if there was an error opening the database connection; otherwise returnsfalse
. Error information can be retrieved using thelastError()
function.- isValid()¶
- Return type:
bool
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Returns
true
if theQSqlDatabase
has a valid driver.Example:
db = QSqlDatabase() print(db.isValid() ) # Returns false db = QSqlDatabase.database("sales") print(db.isValid() # Returns \c true if "sales" connection exists) QSqlDatabase.removeDatabase("sales") print(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
lastError()
.See also
Changes the thread affinity for
QSqlDatabase
and its associated driver. This function returnstrue
when the function succeeds. Event processing will continue in thetargetThread
.During this operation you have to make sure that there is no
QSqlQuery
bound to this instance otherwise theQSqlDatabase
will not be moved to the given thread and the function returnsfalse
.Since the associated driver is derived from QObject, all constraints for moving a QObject to another thread also apply to this function.
See also
moveToThread()Threads and the SQL Module
- numericalPrecisionPolicy()¶
- Return type:
Returns the numericalPrecisionPolicy.
See also
Getter of property
numericalPrecisionPolicyᅟ
.- open()¶
- Return type:
bool
Opens the database connection using the current connection values. Returns
true
on success; otherwise returnsfalse
. Error information can be retrieved usinglastError()
.- open(user, password)
- Parameters:
user – str
password – str
- Return type:
bool
This is an overloaded function.
Opens the database connection using the given
user
name andpassword
. Returnstrue
on success; otherwise returnsfalse
. Error information can be retrieved using thelastError()
function.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.
See also
- password()¶
- Return type:
str
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 theopen()
call, or if no password was used.See also
- port()¶
- Return type:
int
Returns the connection’s port number. The value is undefined if the port number has not been set.
See also
Returns the primary index for table
tablename
. If no primary index exists, an emptyQSqlIndex
is returned.Note
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 documentation for more information.- record(tablename)¶
- Parameters:
tablename – str
- Return type:
Returns a
QSqlRecord
populated with the names of all the fields in the table (or view) calledtablename
. The order in which the fields appear in the record is undefined. If no such table (or view) exists, an empty record is returned.Note
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 documentation for more information.- static registerSqlDriver(name, creator)¶
- Parameters:
name – str
creator –
QSqlDriverCreatorBase
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
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.Example:
QSqlDatabase.registerSqlDriver("MYDRIVER", QSqlDriverCreator()<QSqlDriver>) QVERIFY(QSqlDatabase.drivers().contains("MYDRIVER")) db = QSqlDatabase.addDatabase("MYDRIVER") QVERIFY(db.isValid())
QSqlDatabase
takes ownership of thecreator
pointer, so you mustn’t delete it yourself.See also
- static removeDatabase(connectionName)¶
- Parameters:
connectionName – str
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Removes the database connection
connectionName
from the list of database connections.Warning
There should be no open queries on the database connection when this function is called, otherwise a resource leak will occur.
Example:
# WRONG db = QSqlDatabase.database("sales") query = QSqlQuery("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:
db = QSqlDatabase.database("sales") query = QSqlQuery("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 callingconnectionName()
on the database returned bydatabase()
. Note that if a default database hasn’t been created an invalid database will be returned.See also
database()
connectionName()
Threads and the SQL Module
- rollback()¶
- Return type:
bool
Rolls back a transaction on the database, if the driver supports transactions and a
transaction()
has been started. Returnstrue
if the operation succeeded. Otherwise it returnsfalse
.Note
For some databases, the rollback will fail and return
false
if there is anactive query
using the database for aSELECT
. Make the queryinactive
before doing the rollback.Call
lastError()
to get information about errors.See also
- setConnectOptions([options=""])¶
- Parameters:
options – str
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
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(), andopen()
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 and are described for each plugin in the SQL Database Drivers page.Examples:
db.setConnectOptions("SSL_KEY=client-key.pemSSL_CERT=client-cert.pem;SSL_CA=ca-cert.pem;CLIENT_IGNORE_SPACE=1"); # use an SSL connection to the server if not db.open(): db.setConnectOptions() # clears the connect option string # ... # ... # PostgreSQL connection db.setConnectOptions("requiressl=1") # enable PostgreSQL SSL connections if not db.open(): db.setConnectOptions() # clear options # ... # ... # ODBC connection db.setConnectOptions("SQL_ATTR_ACCESS_MODE=SQL_MODE_READ_ONLYSQL_ATTR_TRACE=SQL_OPT_TRACE_ON"); # set ODBC options if not db.open(): db.setConnectOptions() # don't try to set this option # ...
Refer to the client library documentation for more information about the different options.
See also
- setDatabaseName(name)¶
- Parameters:
name – str
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Sets the connection’s database name to
name
. To have effect, the database name must be set before the connection isopened
. Alternatively, you canclose()
the connection, set the database name, and callopen()
again.Note
The 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:# ... 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.
- setHostName(host)¶
- Parameters:
host – str
Sets the connection’s host name to
host
. To have effect, the host name must be set before the connection isopened
. Alternatively, you canclose()
the connection, set the host name, and callopen()
again.There is no default value.
- setNumericalPrecisionPolicy(precisionPolicy)¶
- Parameters:
precisionPolicy –
NumericalPrecisionPolicy
Sets
numericalPrecisionPolicy
toprecisionPolicy
.See also
Setter of property
numericalPrecisionPolicyᅟ
.- setPassword(password)¶
- Parameters:
password – str
Sets the connection’s password to
password
. To have effect, the password must be set before the connection isopened
. Alternatively, you canclose()
the connection, set the password, and callopen()
again.There is no default value.
Warning
This function stores the password in plain text within Qt. Use the
open()
call that takes a password as parameter to avoid this behavior.- setPort(p)¶
- Parameters:
p – int
Sets the connection’s port number to
port
. To have effect, the port number must be set before the connection isopened
. Alternatively, you canclose()
the connection, set the port number, and callopen()
again..There is no default value.
- setUserName(name)¶
- Parameters:
name – str
Sets the connection’s user name to
name
. To have effect, the user name must be set before the connection isopened
. Alternatively, you canclose()
the connection, set the user name, and callopen()
again.There is no default value.
Returns a list of the database’s tables, system tables and views, as specified by the parameter
type
.See also
Returns a pointer to the associated QThread instance.
- transaction()¶
- Return type:
bool
Begins a transaction on the database if the driver supports transactions. Returns
true
if the operation succeeded. Otherwise it returnsfalse
.See also
- userName()¶
- Return type:
str
Returns the connection’s user name; it may be empty.
See also