2017-03-28 29 views
0

我想在插入數據之前檢查表是否存在。 這是我曾嘗試:如何使用python檢查表是否存在?

def checkTables(tablename): 
    stmt = "SHOW TABLES LIKE %s"%tablename   
    cursor.execute(stmt) 
    result = cursor.fetchone()   
    return result 

但它給了我錯誤說:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ctg_payload3' at line 1

+0

您的語法是否適合參數?見例如http://stackoverflow.com/questions/902408/how-to-use-variables-in-sql-statement-in-python取決於你正在使用哪個數據庫,例如也許'cursor.execute(「SHOW TABLES LIKE?」,(tablename))' – doctorlove

回答

0

也許這是不是最好的方法。

至於我的意見,我會show tables;,然後搜索結果。

而且,我不能執行show tables like tablename;,沒有這樣的語法。

編輯1

如果必須在SQL做到這一點,使用

show table status like 'table_name'; 

'需要對這個SQL。

+0

謝謝你使用這個解決方案 – tintin

+0

不客氣。當你解決問題時,不要忘記標記答案。 – chile

0

試試這個查詢字符串:SHOW TABLES WHERE Tables_in_mydb LIKE '%tablename%'

這個

SELECT table_name 
FROM information_schema.tables 
WHERE table_schema = 'my_database_name' 
AND table_name LIKE '%tablename%' 

好運

0

試試這個。

def checkTables(tablename): 
    stmt = "SHOW TABLES LIKE '%s' "% ('%'+str(tablename)+'%') 
    cursor.execute(stmt) 
    result = cursor.fetchone()   
    return result