Python Forum
PyQt5, QtSql: connection to database does not work
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
PyQt5, QtSql: connection to database does not work
#1
Good evening,

I am not sure whether this is the right section, since my question is not about the GUI part of PyQt, but database (QtSql).

I am trying to get familiar with the PyQt5.QtSql module, because I use PyQt5 a lot and especially QTableViews.
I Tried to set a connection to an existing database on my local machine in order to run some tests.

Althought connection.isOpen() does not return False, it is simply empty and doesn't seem to catch anything from the database. Weird thing is, it doesn't raise any exception either. For example, if I run a query to create a table and then try to print database's tables, it will just return an empty list.

Here is my code and, attached, a screenshot of my environment - in case it might be some problem of paths and filenames.
I already tried to call .addDatabase() with a connection name as parameter, but it doesn't make any difference.

import sys

from PyQt5.QtSql import (QSqlDatabase, QSqlQuery)
from PyQt5.QtWidgets import (
    QApplication,
    QMainWindow,
    QWidget,
    QTableView,
    QPushButton,
    QLabel,
    QHBoxLayout,
    QVBoxLayout,
    QStyle
)


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(title_txt='My First Database App', button_txt='Refresh')
        self.getData()

    def setupUi(self, **kwargs):
        container = QWidget()
        main_layout = QVBoxLayout()

        # Top section
        top_section_layout = QHBoxLayout()
        top_section_container = QWidget()

        top_section_layout.addWidget(QLabel(kwargs['title_txt']))
        refresh_btn = QPushButton(kwargs['button_txt'])
        refresh_btn.setIcon(QApplication.style().standardIcon(QStyle.SP_BrowserReload))
        refresh_btn.setFixedSize(refresh_btn.sizeHint())
        top_section_layout.addWidget(refresh_btn)

        top_section_container.setLayout(top_section_layout)

        # Table section
        search_result_tbl = QTableView()

        # Wrapping up
        main_layout.addWidget(top_section_container)
        main_layout.addWidget(search_result_tbl)
        container.setLayout(main_layout)
        self.setCentralWidget(container)

    def getData(self):
        connection = QSqlDatabase.addDatabase('QSQLITE', 'testDB.sqlite')
        connection.open()

        if not connection.isOpen():
            print('Connection error occurred.')
        else:
            print(connection.tables())

    def setObjectsName(self):
        pass


app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()
   
Reply
#2
change getData to

    def getData(self):
        connection = QSqlDatabase.addDatabase('QSQLITE')
        connection.setDatabaseName('testDB.sqlite')
        connection.open()
 
        if not connection.isOpen():
            print('Connection error occurred.')
        else:
            print(connection.tables())
Reply
#3
Thank you, you'v been most helpful, it worked. Would you mind explaining the difference between stating the name in the .addDatabase() method and doing the same with in a separate .setDatabaseName()?
Reply
#4
QSqlDatabase.addDatabase(type, connection name)

you can give your connection a name, this is an option.

If connectionName is not specified, the new connection becomes the default connection

QSqlDatabase.setDatabaseName(filepath)
Reply
#5
Connection names are used to manage connections, not to select a database. When you open a connection it first checks if there is a connection using the same name. If there is, it shuts down the existing connection before opening the new. If you ever want to have multiple connections open at the same time you'll need to provide unique names for each connection. I don't think this option is used often.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  PyQt5 form not displaying my data from SQLite3 Database Linuxdesire 2 4,928 Jan-10-2023, 09:51 PM
Last Post: gradlon93
  [PyQt] [Solved]Make certain columns Un-editable in QtSql Extra 7 3,004 May-28-2022, 05:19 PM
Last Post: Extra
  Huge code problems (buttons(PyQt5),PyQt5 Threads, Windows etc) ZenWoR 0 2,785 Apr-06-2019, 11:15 PM
Last Post: ZenWoR
  [PyQt] How to print a QtSql.QSqlQuery() from python ThunderBlitz 0 4,884 Mar-22-2017, 01:07 PM
Last Post: ThunderBlitz

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020