Search code examples
pythonpyqtmariadbodbcqsqldatabase

QSqlDatabase connection


I have a server with a MariaDB Database. Then I have a python program who run in a client where I have this code:

def Connect():
    
    #   Credential reading from register
    servHost = RegRead("servHost")
    servPort = RegRead("servPort")
    dbName = RegRead("dbName")
    __dbUser = RegRead("dbUser")
    __dbPass = RegRead("dbPass")

    con = QSqlDatabase.addDatabase('QODBC3')
    driver = "DRIVER={MariaDB ODBC 3.1 Driver};"
    database = f"Database={dbName};"
    databaseName = driver+database
    con.setDatabaseName(databaseName)
    con.setHostName(servHost)
    con.setPort(servPort)
    if con.open(__dbUser, __dbPass):
        print("Connected")
        return True
    else:
        return False

I have made my program in a pc where I had both parts, so the database was in localhost and my pc was working as server and client at same time, then I changed it to a defined host. In my pc worked everything, but now that I have separeted server and client, I have problem to connect the client. The method Connect() return False and I don't understand what I am missing. I also remember that I installed a lot of things to let this work in my pc, but it was a lot of time ago and I don't remember what I did. In the client, I have installed MariaDB ODBC Connector, I have the Driver "MariaDB ODBC 3.1 Driver" and made an User DNS who correctly connect to the database, but does not when it run in my program. It run in my pc, so my code should be right. I think I missed some installation, maybe about Driver or some package, but I don't know what. Server is working too because I can make an User DNS. I did NOT install MariaDB Server (and I would not if not necessary). I have not installed anything except ODBC Connector and I imported only QSqlDatabase package.


Solution

  • I solved it. The method setHostName and the method setPort seem not to work. I think that it's because it require a QString object as parameter. I solved it adding the Host Name and Port to driver in this way

    def Connect():
        
        #   Credential reading from register
        servHost = RegRead("servHost")
        servPort = RegRead("servPort")
        dbName = RegRead("dbName")
        __dbUser = RegRead("dbUser")
        __dbPass = RegRead("dbPass")
    
        con = QSqlDatabase.addDatabase('QODBC3')
        driver = "DRIVER={MariaDB ODBC 3.1 Driver};"+f"Server={servHost};Port={servPort};"    # This is the edit
        database = f"Database={dbName};"
        databaseName = driver+database
        con.setDatabaseName(databaseName)
        if con.open(__dbUser, __dbPass):
            print("Connected")
            return True
        else:
            return False