Search code examples
pythonmysqlcountsqlalchemystring-formatting

reformat row count in sqalchemy


I'm running a simple command to fetch and print the number of rows in a table within a MySQL db so that RunDeck can log it, and was hoping for either some help with formatting the result or a prettier way to do it.

from sqlalchemy import create_engine

devhost = 'host'
devuser = 'user'
devpassword = 'scipiodestroyedhannibalatzama'

engine = f"mysql+pymysql://{devuser}:{devpassword}@{devhost}/germans_got_lucky"
connection = create_engine(engine)

rows = str(connection.execute("SELECT COUNT(Day) FROM teutoburg_forest").fetchall())
    print(rows)

returns

[(1706,)]

but I'd like it to return

1706

Is there a simple way to do this?


Solution

  • Three possibilities here, first:

    from sqlalchemy import create_engine
    
    devhost = 'host'
    devuser = 'user'
    devpassword = 'scipiodestroyedhannibalatzama'
    
    engine = f"mysql+pymysql://{devuser}:{devpassword}@{devhost}/germans_got_lucky"
    connection = create_engine(engine)
    
    rows = len(connection.execute("SELECT Day FROM teutoburg_forest").fetchall())
    print(rows)
    

    The second:

    from sqlalchemy import create_engine
    
    devhost = 'host'
    devuser = 'user'
    devpassword = 'scipiodestroyedhannibalatzama'
    
    engine = f"mysql+pymysql://{devuser}:{devpassword}@{devhost}/germans_got_lucky"
    connection = create_engine(engine)
    
    rows = connection.execute("SELECT Day FROM teutoburg_forest").count
    print(rows)
    

    or the third:

    from sqlalchemy import create_engine
    
    devhost = 'host'
    devuser = 'user'
    devpassword = 'scipiodestroyedhannibalatzama'
    
    engine = f"mysql+pymysql://{devuser}:{devpassword}@{devhost}/germans_got_lucky"
    connection = create_engine(engine)
    
    rows = connection.execute("SELECT COUNT(Day) FROM teutoburg_forest").fetchone()
    print(rows[0])