0

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?

zabada
  • 67
  • 1
  • 10

3 Answers3

1

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])
hd1
  • 33,938
  • 5
  • 80
  • 91
1

.scalar() gives what you need:

conn.execute(text("SELECT count(tickers.ticker) FROM tickers")).scalar()

I also used text() clause as it is required in sqlalchemy>=1.4

van
  • 74,297
  • 13
  • 168
  • 171
0

This answer worked perfectly to strip away the unneeded characters.

rows = str(connection.execute("SELECT COUNT(Day) FROM teutoburg_forest").fetchall())
print(rows)
[(1706,)]
print(''.join([n for n in rows if n.isdigit()]))
1706
zabada
  • 67
  • 1
  • 10