3

I have this following python code with pymysql

    cursor=conn.cursor()
    cursor.execute("""select count(distinct `session_id`) from innodb.fh where `cs-uri-stem` like "/detail%"   """)
    cursor.fetchone()

which is working fine. But i just wonder how to print out the result for my sql statement. it should print out 1204. I tried the following but it is not working:

       results = cursor.execute("""select count(distinct `session_id`) from innodb.fh where `cs-uri-stem` like "/detail%"   """)
       print (results)

thx!

Andrii Omelchenko
  • 13,183
  • 12
  • 43
  • 79
yingnan liu
  • 409
  • 1
  • 8
  • 18
  • What are you triyng to extract? Will fetchall() do any good? – Pax Vobiscum Apr 03 '16 at 02:04
  • probably i did not explain my questions clearly. The sql statement in my code would return "1204" as the result. But i just wonder how I could print out this 1204 thing in python – yingnan liu Apr 03 '16 at 02:09
  • If you're trying to get the number of rows affected when you do `cursor.execute()`, note that this depends on the database connector you are using. For Postgres with psycopg2, for example you can use [`cursor.rowcount`](http://stackoverflow.com/questions/9222256/how-do-i-know-if-i-have-successfully-created-a-table-python-psycopg2/36146253#36146253). – Akshat Mahajan Apr 03 '16 at 02:10
  • So clarify. What database connector software are you using? PyMySQL? Psycopg2? More simply: what library are you using to get `cursor` from? – Akshat Mahajan Apr 03 '16 at 02:11
  • @AkshatMahajan hi, i used pymysql – yingnan liu Apr 03 '16 at 02:12

1 Answers1

1

The PyMySQL cursor defines an attribute called rowcount, as can be seen in the source code.

Immediately after cursor.execute(), you can call cursor.rowcount to get the number of rows affected by the SQL statement.

Akshat Mahajan
  • 9,543
  • 4
  • 35
  • 44