连接数据库
要通过QSqlQuery 或QSqlQueryModel 访问数据库,需创建并打开一个或多个数据库连接。数据库连接通常通过连接名称来标识,而非数据库名称。 您可以对同一数据库建立多个连接。QSqlDatabase 还支持“默认连接”的概念,即一个未命名的连接。在调用QSqlQuery 或QSqlQueryModel 这些需要连接名称作为参数的成员函数时,若未传入连接名称,则将使用默认连接。当您的应用程序仅需一个数据库连接时,创建默认连接会非常方便。
请注意创建连接与打开连接之间的区别。创建连接是指创建QSqlDatabase 类的实例。该连接在被打开之前无法使用。以下代码片段演示了如何创建默认连接并将其打开:
QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
db.setHostName("bigblue");
db.setDatabaseName("flightdb");
db.setUserName("acarlson");
db.setPassword("1uTbSbAs");
bool ok = db.open();第一行创建连接对象,最后一行将其打开以供使用。其间,我们初始化了一些连接信息,包括database name 、host name 、user name 和password 。在此示例中,我们连接到主机bigblue 上的MySQL数据库flightdb 。传递给addDatabase()的"QMYSQL" 参数指定了连接所使用的数据库驱动程序类型。 Qt 随附的数据库驱动程序列表请参见“支持的数据库驱动程序”表格。
由于我们未向addDatabase() 传递第二个参数(即连接名称),因此代码片段中的连接将采用默认连接。例如,这里我们建立两个名为"first" 和"second" 的 MySQL 数据库连接:
QSqlDatabase firstDB = QSqlDatabase::addDatabase("QMYSQL", "first");
QSqlDatabase secondDB = QSqlDatabase::addDatabase("QMYSQL", "second");初始化这些连接后,需分别调用open() 来建立活动连接。若open() 调用失败,则返回false 。此时,请调用QSqlDatabase::lastError() 以获取错误信息。
建立连接后,我们可以在任何位置调用静态函数QSqlDatabase::database(),并传入连接名称,以获取该数据库连接的指针。如果未传入连接名称,则返回默认连接。例如:
QSqlDatabase defaultDB = QSqlDatabase::database();
QSqlDatabase firstDB = QSqlDatabase::database("first");
QSqlDatabase secondDB = QSqlDatabase::database("second");要删除数据库连接,请先使用QSqlDatabase::close() 关闭数据库,然后使用静态方法QSqlDatabase::removeDatabase() 将其删除。
© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.