3

我制作了一个函数,它使用cursor.rowcountPython 中的函数计算表中的行数。现在我想将它应用到我通过 %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 部分是错误的。

4

1 回答 1

9
query = "SELECT COUNT(*) from `%s`" %table
cursor.execute(query)             #execute query separately
res = cursor.fetchone()
total_rows = res[0]      #total rows
于 2012-10-08T23:34:41.803 回答