PyQt5创建数据库GUI时遇QSqlQuery::exec: database not open报错求助
Hey, let's break down why you're hitting this error and how to fix it quickly. The core problem here is that you've set up the database name, but you haven't actually opened a connection to the database before trying to run your query. PyQt's QSqlDatabase needs an active open connection to execute any SQL commands.
Step 1: Add the Database Driver (If You Haven't Already)
First, make sure you've initialized the database with the correct driver. For SQLite (which you're using with .db file), you need to call addDatabase() first—this is a super common missing step:
# Add this line before setting the database name self.db = QtSql.QSqlDatabase.addDatabase("QSQLITE")
Step 2: Open the Database Connection
After setting the database name, you must explicitly open the connection. Always check if the open operation succeeds to catch issues like missing files or permission problems:
self.db.setDatabaseName('demodatabase.db') # Open the database and validate the connection if not self.db.open(): print(f"Failed to open database: {self.db.lastError().text()}") return # Exit early if connection fails # Now proceed with your table creation query self.query = QtSql.QSqlQuery(self.db) create_table_sql = """ CREATE TABLE new1 ( id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE NOT NULL, name VARCHAR(100) ) """ if self.query.exec_(create_table_sql): print("Table 'new1' created successfully!") else: print(f"Failed to create table: {self.query.lastError().text()}")
Quick Tips to Avoid Future Headaches
- Never skip connection checks: Don't assume
db.open()will work—use its return value andlastError()to debug issues like corrupted database files or read-only permissions. - Reuse connections: Stick to one open connection for your app's lifecycle instead of creating multiple connections unnecessarily.
- Clean up on exit: When your app closes, call
self.db.close()to properly release the database connection.
内容的提问来源于stack exchange,提问作者james morgan

