2012-10-08 33 views
2

我已經使用Python中的cursor.rowcount函數計算了表中行的數量。現在我想將其應用於通過%s選擇的表格。問題是我不知道如何應用它。這是我正在使用的示例。Python/MySQL-如何正確使用%s來計算行

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") 

基本上它所做的所有輸入數據到一個文本文件中的MySQL表,現在我想要的功能同時打印行數爲特定表。它得到一個錯誤消息,說錯誤的MySQL語法,所以這段代碼對於rowcount部分是錯誤的。

+0

'select count_name(*)from table_name' should be it。 –

+0

因此,將cursor.execute(「SELECT * FROM%s」,table)替換爲cursor.execute(「SELECT COUNT(*)FROM table_name)? – Hayden

+0

我編輯了我的答案,試試。 –

回答

4
query = "SELECT COUNT(*) from `%s`" %table 
cursor.execute(query)    #execute query separately 
res = cursor.fetchone() 
total_rows = res[0]  #total rows