Michael Stern
Michael Stern

Reputation: 487

Why would MariaDB return nothing through Python to a query that works fine every other way?

I have a functioning MariaDB server. It works as expected when logged into locally with its own client software, or when connected to from a remote machine via, for example, Navicat. When connected in these ways, it responds to all SELECT and INSERT commands as expected.

However I can not get it to respond to Python and it does not even return an error.

Here is test code:

#!/usr/bin/python

import mysql.connector as mariadb
# import mariadb

class dbQuery:

    def __init__(self):
        try:
            self.mariadb_connection = mariadb.connect(host='127.0.0.1', port=8457, user='root', password='XXXXX', database='empowerment')
            self.cursor = self.mariadb_connection.cursor()
        except:
            print("Error")

    def query(self):
        query = "SELECT 1+1;"
        try:
            ans = self.cursor.execute(query)
        except:
            print("Error")
        print("ans1: ",ans)
        return ans

    def __del__(self):
        self.mariadb_connection.close()

thisQuery = dbQuery()
ans = thisQuery.query()
print("ans2: ",ans)

ans1 and ans2 both print None with both mysql.connector and with the (beta) mariadb connector. None of the exceptions are ever thrown. If I print the connection or cursor variables, they seem to have valid contents at the appropriate points in the code. Only the output of execute seems wrong. This is on Raspberry Pi OS, if that matters.

What might I be missing?

Upvotes: 0

Views: 1033

Answers (1)

ywbaek
ywbaek

Reputation: 3031

mysql.connector is based on the Python Database API Specification v2.0 (link)
And execute method returns None
To get the result of the query, you need to use method like fetchall or
you need to iterate through the cursor object itself.
So your query method should be something like the following:

    def query(self):
        query = "SELECT 1+1;"
        try:
            self.cursor.execute(query)
            ans = self.cursor.fetchall()
        except:
            print("Error")
        print("ans1: ",ans)
        return ans

Upvotes: 1

Related Questions