Search code examples
pythonmysqlmysql-connector-python

Python: How to access MySQL DB table using SQLAlchemy


I am making a python GUI that will look up the the status of a helpdesk ticket in a MySQL database. I connected python to an existing MySQL database with SQLAlchemy using the code below.

conn = mysql.connector.connect(user='root',
                               password='stuff',host='127.0.0.1',
                               database='mydb')
c = conn.cursor()

I only need access to one of the columns, ticket_id, in a table called tickets. Basically I want to do this:

SELECT ticket_status FROM  tickets WHERE ticket_id = 123; 

What would be simplest way to do this?


Solution

  • The following code should work at fetching a single value. If you realize later you need to fetch more than one value you can change fetchone() to fetchall()

    try:
    
        sql = '''
            SELECT ticket_status FROM tickets WHERE ticket_id = 123
                    '''
        c.execute(sql)
        result = c.fetchone()
    except Exception as e:
        raise Exception(e)