2017-03-28 12 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("テーブルを表示する? "、(tablename))' – doctorlove

答えて

0

は多分それが最善の方法ではありません。

私の意見としては、show tables;とし、その結果を検索します。

show tables like tablename;を実行することはできません。そのような構文はありません。

編集1

あなたは

show table status like 'table_name'; 

'を使用し、SQLでそれを行う必要がある場合は、このSQLのために必要とされています。

+0

ありがとうございますこのソリューションは – tintin

+0

ようこそ。問題を解決するときに答えを記入することを忘れないでください。 – chile

0

このクエリ文字列を試してみてください:SHOW TABLES WHERE Tables_in_mydb LIKE '%tablename%'または

この1

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 
関連する問題