5

I have made a function which counts the amount of rows there are in a table using the cursor.rowcountfunction in Python. Now I want to apply that to tables I choose through %s. The problem is that I don't know how to apply it. Here is the sample I am working with.

def data_input (table):
    cursor.execute ("USE database")
    cursor.execute ("TRUNCATE TABLE table1")
    cursor.execute ("TRUNCATE TABLE table2")
    cursor.execute ("LOAD DATA LOCAL INFILE 'table1data' INTO TABLE table1 FIELDS TERMINATED BY '\t' LINES TERMINATED BY '\n' (field1, field2, field3, field4, field5)")
    cursor.execute ("LOAD DATA LOCAL INFILE 'table2data' INTO TABLE table2 FIELDS TERMINATED BY '\t' LINES TERMINATED BY '\n' (field1, field2, field3)")
    cursor.execute ("SELECT * FROM %s", table)
    print cursor.rowcount


data_input ("table1")

Basically what it already does is input all the data into tables in MySQL from a text file, now I want the function to also print the number of rows for a particular table. It is getting an error message saying wrong MySQL syntax so this code is wrong for the rowcount part.

3
  • select count(*) from table_name should do it. Commented Oct 8, 2012 at 23:31
  • So replace cursor.execute ("SELECT * FROM %s", table) to cursor.execute ("SELECT COUNT (*) FROM table_name)? Commented Oct 8, 2012 at 23:40
  • I've edited my answer, try that. Commented Oct 8, 2012 at 23:43

1 Answer 1

12
query = "SELECT COUNT(*) from `%s`" %table
cursor.execute(query)             #execute query separately
res = cursor.fetchone()
total_rows = res[0]      #total rows
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.