PySide.QtSql.QSqlDatabase class represents a connection to a database.
PySide.QtSql.QSqlDatabase class provides an interface for accessing a database through a connection. An instance of PySide.QtSql.QSqlDatabase represents the connection. The connection provides access to the database via one of the supported database drivers , which are derived from PySide.QtSql.QSqlDriver . Alternatively, you can subclass your own database driver from PySide.QtSql.QSqlDriver 。见 How to Write Your Own Database Driver 了解更多信息。
Create a connection (i.e., an instance of PySide.QtSql.QSqlDatabase ) by calling one of the static PySide.QtSql.QSqlDatabase.addDatabase() functions, where you specify the driver or type of driver to use (i.e., what kind of database will you access?) 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. PySide.QtSql.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 PySide.QtSql.QSqlDatabase.addDatabase() . Subsequently, when you call any static member function that takes the connection name argument, if you don't pass the connection name argument, the default connection is assumed. 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 PySide.QtSql.QSqlDatabase object has been created, set the connection parameters with PySide.QtSql.QSqlDatabase.setDatabaseName() , PySide.QtSql.QSqlDatabase.setUserName() , PySide.QtSql.QSqlDatabase.setPassword() , PySide.QtSql.QSqlDatabase.setHostName() , PySide.QtSql.QSqlDatabase.setPort() ,和 PySide.QtSql.QSqlDatabase.setConnectOptions() . Then call PySide.QtSql.QSqlDatabase.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 PySide.QtSql.QSqlDatabase.addDatabase() . Subsequently, you can get the default connection by calling PySide.QtSql.QSqlDatabase.database() without the connection name argument:
db = QSqlDatabase.database()
PySide.QtSql.QSqlDatabase is a value class. Changes made to a database connection via one instance of PySide.QtSql.QSqlDatabase will affect other instances of PySide.QtSql.QSqlDatabase that represent the same connection. Use PySide.QtSql.QSqlDatabase.cloneDatabase() to create an independent database connection based on an existing one.
If you create multiple database connections, specify a unique connection name for each one, when you call PySide.QtSql.QSqlDatabase.addDatabase() 。使用 PySide.QtSql.QSqlDatabase.database() with a connection name to get that connection. Use PySide.QtSql.QSqlDatabase.removeDatabase() with a connection name to remove a connection. PySide.QtSql.QSqlDatabase outputs a warning if you try to remove a connection referenced by other PySide.QtSql.QSqlDatabase objects. Use PySide.QtSql.QSqlDatabase.contains() to see if a given connection name is in the list of connections.
Once a connection is established, you can call PySide.QtSql.QSqlDatabase.tables() to get the list of tables in the database, call PySide.QtSql.QSqlDatabase.primaryIndex() to get a table's primary index, and call PySide.QtSql.QSqlDatabase.record() to get meta-information about a table's fields (e.g., field names).
注意
QSqlDatabase.exec() is deprecated. Use QSqlQuery.exec() 代替。
If the driver supports transactions, use PySide.QtSql.QSqlDatabase.transaction() to start a transaction, and PySide.QtSql.QSqlDatabase.commit() or PySide.QtSql.QSqlDatabase.rollback() to complete it. Use PySide.QtSql.QSqlDriver.hasFeature() to ask if the driver supports transactions. 注意: When using transactions, you must start the transaction before you create your query.
If an error occurrs, PySide.QtSql.QSqlDatabase.lastError() will return information about it.
Get the names of the available SQL drivers with PySide.QtSql.QSqlDatabase.drivers() . Check for the presence of a particular driver with PySide.QtSql.QSqlDatabase.isDriverAvailable() . If you have created your own custom driver, you must register it with PySide.QtSql.QSqlDatabase.registerSqlDriver() .
另请参阅
PySide.QtSql.QSqlDriver PySide.QtSql.QSqlQuery QtSql Module 线程和 SQL 模块
| 参数: |
|
|---|
Creates an empty, invalid PySide.QtSql.QSqlDatabase 对象。使用 PySide.QtSql.QSqlDatabase.addDatabase() , PySide.QtSql.QSqlDatabase.removeDatabase() ,和 PySide.QtSql.QSqlDatabase.database() to get valid PySide.QtSql.QSqlDatabase 对象。
这是重载函数。
Creates a database connection using the given driver .
Creates a copy of other .
这是重载函数。
创建 PySide.QtSql.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 |
| QSQLITE2 | SQLite version 2 |
| QTDS | Sybase Adaptive Server |
Additional third party drivers, including your own custom drivers, can be loaded dynamically.
| 参数: |
|
|---|---|
| 返回类型: |
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, PySide.QtSql.QSqlDatabase.isValid() returns false.
若 connectionName is not specified, the new connection becomes the default connection for the application, and subsequent calls to PySide.QtSql.QSqlDatabase.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 PySide.QtSql.QSqlDatabase.setDatabaseName() , PySide.QtSql.QSqlDatabase.setUserName() , PySide.QtSql.QSqlDatabase.setPassword() , PySide.QtSql.QSqlDatabase.setHostName() , PySide.QtSql.QSqlDatabase.setPort() ,和 PySide.QtSql.QSqlDatabase.setConnectOptions() , and, finally, PySide.QtSql.QSqlDatabase.open() .
| 参数: |
|
|---|---|
| 返回类型: |
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:
#include "qtdir/src/sql/drivers/psql/qsql_psql.cpp"
con = PQconnectdb("host=server user=bart password=simpson dbname=springfield")
drv = QPSQLDriver(con)
db = QSqlDatabase.addDatabase(drv) # becomes the new 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, PySide.QtSql.QSqlDatabase.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 |
| QTDS | QTDSDriver | LOGINREC *loginRecord, DBPROCESS *dbProcess, const PySide.QtCore.QString &hostName | qsql_tds.cpp |
| QSQLITE | QSQLiteDriver | sqlite *connection | qsql_sqlite.cpp |
| QIBASE | QIBaseDriver | isc_db_handle connection | qsql_ibase.cpp |
The host name (or service name) is needed when constructing the QTDSDriver for creating new connections for internal queries. This is to prevent blocking when several PySide.QtSql.QSqlQuery objects are used simultaneously.
警告
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 PySide.QtSql.QSqlDatabase.removeDatabase() .
| 参数: |
|
|---|---|
| 返回类型: |
Clones the database connection other and and stores it as connectionName . All the settings from the original database, e.g. PySide.QtSql.QSqlDatabase.databaseName() , PySide.QtSql.QSqlDatabase.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 PySide.QtSql.QSqlDatabase.open() .
Closes the database connection, freeing any resources acquired, and invalidating any existing PySide.QtSql.QSqlQuery objects that are used with the database.
This will also affect copies of this PySide.QtSql.QSqlDatabase 对象。
| 返回类型: | PySide.QtCore.bool |
|---|
Commits a transaction to the database if the driver supports transactions and a PySide.QtSql.QSqlDatabase.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.
调用 PySide.QtSql.QSqlDatabase.lastError() to get information about errors.
| 返回类型: | unicode |
|---|
Returns the connection options string used for this connection. The string may be empty.
| 返回类型: | unicode |
|---|
Returns the connection name, which may be empty. 注意: The connection name is not the database name .
| 返回类型: | 字符串列表 |
|---|
Returns a list containing the names of all connections.
| 参数: | connectionName – unicode |
|---|---|
| 返回类型: | PySide.QtCore.bool |
Returns true if the list of database connections contains connectionName ;否则返回 false。
| 参数: |
|
|---|---|
| 返回类型: |
Returns the database connection called connectionName . The database connection must have been previously added with PySide.QtSql.QSqlDatabase.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.
另请参阅
PySide.QtSql.QSqlDatabase.isOpen() 线程和 SQL 模块
| 返回类型: | unicode |
|---|
Returns the connection's database name, which may be empty. 注意: The database name is not the connection name.
| 返回类型: | PySide.QtSql.QSqlDriver |
|---|
Returns the database driver used to access the database connection.
| 返回类型: | unicode |
|---|
Returns the connection's driver name.
| 返回类型: | 字符串列表 |
|---|
Returns a list of all the available database drivers.
| 参数: | query – unicode |
|---|---|
| 返回类型: | PySide.QtSql.QSqlQuery |
Executes a SQL statement on the database and returns a PySide.QtSql.QSqlQuery 对象。使用 PySide.QtSql.QSqlDatabase.lastError() to retrieve error information. If query is empty, an empty, invalid query is returned and PySide.QtSql.QSqlDatabase.lastError() is not affected.
| 返回类型: | unicode |
|---|
Returns the connection's host name; it may be empty.
| 参数: | name – unicode |
|---|---|
| 返回类型: | PySide.QtCore.bool |
Returns true if a driver called name is available; otherwise returns false.
| 返回类型: | PySide.QtCore.bool |
|---|
Returns true if the database connection is currently open; otherwise returns false.
| 返回类型: | PySide.QtCore.bool |
|---|
Returns true if there was an error opening the database connection; otherwise returns false. Error information can be retrieved using the PySide.QtSql.QSqlDatabase.lastError() 函数。
| 返回类型: | PySide.QtCore.bool |
|---|
返回 true 若 PySide.QtSql.QSqlDatabase has a valid driver.
范例:
db = QSqlDatabase()
print(db.isValid()) # Returns False
db = QSqlDatabase.database("sales")
print(db.isValid()) # Returns True if "sales" connection exists
QSqlDatabase.removeDatabase("sales")
print(db.isValid()) # Returns False
| 返回类型: | PySide.QtSql.QSqlError |
|---|
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() .
| 返回类型: | PySide.QtSql.QSql.NumericalPrecisionPolicy |
|---|
Returns the current default precision policy for the database connection.
另请参阅
QSql.NumericalPrecisionPolicy PySide.QtSql.QSqlDatabase.setNumericalPrecisionPolicy() QSqlQuery.numericalPrecisionPolicy() QSqlQuery.setNumericalPrecisionPolicy()
| 参数: |
|
|---|---|
| 返回类型: |
PySide.QtCore.bool |
这是重载函数。
Opens the database connection using the given user name and password . Returns true on success; otherwise returns false. Error information can be retrieved using the PySide.QtSql.QSqlDatabase.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.
| 返回类型: | PySide.QtCore.bool |
|---|
Opens the database connection using the current connection values. Returns true on success; otherwise returns false. Error information can be retrieved using PySide.QtSql.QSqlDatabase.lastError() .
| 返回类型: | unicode |
|---|
Returns the connection's password. If the password was not set with PySide.QtSql.QSqlDatabase.setPassword() , and if the password was given in the PySide.QtSql.QSqlDatabase.open() call, or if no password was used, an empty string is returned.
| 返回类型: | PySide.QtCore.int |
|---|
Returns the connection's port number. The value is undefined if the port number has not been set.
| 参数: | tablename – unicode |
|---|---|
| 返回类型: | PySide.QtSql.QSqlIndex |
Returns the primary index for table tablename . If no primary index exists an empty PySide.QtSql.QSqlIndex 被返回。
| 参数: | tablename – unicode |
|---|---|
| 返回类型: | PySide.QtSql.QSqlRecord |
返回 PySide.QtSql.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.
| 参数: |
|
|---|
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.
范例:
class MyDatabaseDriverCreatorBase(QtSql.QSqlDriverCreatorBase):
...
def createObject(self):
return MyDatabaseDriver()
mydriver = MyDatabaseDriverCreatorBase()
QtSql.QSqlDatabase.registerSqlDriver("MYDRIVER", mydriver)
db = QtSql.QSqlDatabase.addDatabase("MYDRIVER")
PySide.QtSql.QSqlDatabase 拥有所有权对于 creator pointer, so you mustn't delete it yourself.
| 参数: | connectionName – unicode |
|---|
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
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 PySide.QtSql.QSqlDatabase.addDatabase() not specifying a connection name, you can retrieve the default connection name by calling PySide.QtSql.QSqlDatabase.connectionName() on the database returned by PySide.QtSql.QSqlDatabase.database() . Note that if a default database hasn't been created an invalid database will be returned.
| 返回类型: | PySide.QtCore.bool |
|---|
Rolls back a transaction on the database, if the driver supports transactions and a PySide.QtSql.QSqlDatabase.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.
调用 PySide.QtSql.QSqlDatabase.lastError() to get information about errors.
| 参数: | options – unicode |
|---|
Sets database-specific options . This must be done before the connection is opened or it has no effect (or you can PySide.QtSql.QSqlDatabase.close() the connection, call this function and PySide.QtSql.QSqlDatabase.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:
范例:
...
# MySQL connection
db.setConnectOptions("CLIENT_SSL=1;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
# set ODBC options
db.setConnectOptions("SQL_ATTR_ACCESS_MODE=SQL_MODE_READ_ONLY;SQL_ATTR_TRACE=SQL_OPT_TRACE_ON")
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.
| 参数: | name – unicode |
|---|
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 PySide.QtSql.QSqlDatabase.close() the connection, set the database name, and call PySide.QtSql.QSqlDatabase.open() 再次。 注意: database name is not the connection name . The connection name must be passed to PySide.QtSql.QSqlDatabase.addDatabase() at connection object create time.
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)};FIL={MS Access};DBQ=myaccessfile.mdb")
if db.open():
# success!
pass
...
There is no default value.
| 参数: | host – unicode |
|---|
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 PySide.QtSql.QSqlDatabase.close() the connection, set the host name, and call PySide.QtSql.QSqlDatabase.open() 再次。
There is no default value.
| 参数: | precisionPolicy – PySide.QtSql.QSql.NumericalPrecisionPolicy |
|---|
| 参数: | password – unicode |
|---|
Sets the connection's password to password . To have effect, the password must be set before the connection is opened . Alternatively, you can PySide.QtSql.QSqlDatabase.close() the connection, set the password, and call PySide.QtSql.QSqlDatabase.open() 再次。
There is no default value.
警告
This function stores the password in plain text within Qt. Use the PySide.QtSql.QSqlDatabase.open() call that takes a password as parameter to avoid this behavior.
| 参数: | p – PySide.QtCore.int |
|---|
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 PySide.QtSql.QSqlDatabase.close() the connection, set the port number, and call PySide.QtSql.QSqlDatabase.open() again..
There is no default value.
| 参数: | name – unicode |
|---|
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 PySide.QtSql.QSqlDatabase.close() the connection, set the user name, and call PySide.QtSql.QSqlDatabase.open() 再次。
There is no default value.
| 参数: | type – PySide.QtSql.QSql.TableType |
|---|---|
| 返回类型: | 字符串列表 |
| 返回类型: | PySide.QtCore.bool |
|---|
Begins a transaction on the database if the driver supports transactions. Returns true if the operation succeeded. Otherwise it returns false .
| 返回类型: | unicode |
|---|
Returns the connection's user name; it may be empty.