python - 如何检查表是否存在?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17044259/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:17:34  来源:igfitidea点击:

python - how to check if table exists?

pythonsql

提问by user1386966

I'm using this function :

我正在使用这个功能:

def checker(name,s)
        MY_T = "SELECT count(*) FROM `"+session.SessionInfo.Name where EventName='"+name+"'"

I want to check if the table exists, how can I do it ? I saw some examples using : XXXX.execute()what does it mean?

我想检查表是否存在,我该怎么做?我看到一些例子使用:XXXX.execute()这是什么意思?

Here is what I saw :

这是我看到的:

query = cursor.execute("""SELECT count(*) FROM scan WHERE prefix = %s and code_id = %s and answer = %s and station_id = %s""",
                          (prefix, code_id, answer, station,))
        if query != 1:

I tried printing MY_T to see if it returns -1 for example but it just prints "select count (*)...... "

我尝试打印 MY_T 以查看它是否返回 -1 例如,但它只是打印 "select count (*)...... "

How can I check it? Any help would be very appreciated.

我该如何检查?任何帮助将不胜感激。

采纳答案by feathj

Use the "TABLES" information schema view. http://dev.mysql.com/doc/refman/5.0/en/information-schema.html

使用“TABLES”信息架构视图。 http://dev.mysql.com/doc/refman/5.0/en/information-schema.html

SELECT * FROM information_schema.tables
WHERE table_name = 'YOUR TABLE'

You can apply this view to your code by doing something like the following:

您可以通过执行以下操作将此视图应用于您的代码:

def checkTableExists(dbcon, tablename):
    dbcur = dbcon.cursor()
    dbcur.execute("""
        SELECT COUNT(*)
        FROM information_schema.tables
        WHERE table_name = '{0}'
        """.format(tablename.replace('\'', '\'\'')))
    if dbcur.fetchone()[0] == 1:
        dbcur.close()
        return True

    dbcur.close()
    return False

回答by Alberto Megía

If you are using Python-MySQL (MySQLdb) -> http://mysql-python.sourceforge.net/MySQLdb.html

如果您使用的是 Python-MySQL (MySQLdb) -> http://mysql-python.sourceforge.net/MySQLdb.html

cursor.execute() is the method to run queries with MySQLdb, Python MySQL driver. You can pass two arguments, like:

cursor.execute() 是使用 MySQLdb、Python MySQL 驱动程序运行查询的方法。您可以传递两个参数,例如:

cursor.execute(statement, parameters)

And will execute "statement" parsing "parameters" to the statement. You need to have opened a database connection and also open a cursor

并将执行“语句”解析“参数”到语句。您需要打开一个数据库连接并打开一个游标

I think you can use MySQL's statement: SHOW TABLES LIKE 'tablename';

我认为你可以使用 MySQL 的语句:SHOW TABLES LIKE 'tablename';

stmt = "SHOW TABLES LIKE 'tableName'"
cursor.execute(stmt)
result = cursor.fetchone()
if result:
    # there is a table named "tableName"
else:
    # there are no tables named "tableName"

EDIT: there will other Python drivers with similar behaviour. Look for yours :)

编辑:会有其他具有类似行为的 Python 驱动程序。寻找你的:)

回答by Jens M.

I found that this works well with Python 3.6 and MySql 5.7:

我发现这适用于 Python 3.6 和 MySql 5.7:

table = 'myTable'
_SQL = """SHOW TABLES"""
cursor.execute(_SQL)
results = cursor.fetchall()

print('All existing tables:', results) # Returned as a list of tuples

results_list = [item[0] for item in results] # Conversion to list of str

if table in results_list:
    print(table, 'was found!')
else:
    print(table, 'was NOT found!')

回答by Wendao Liu

Above answer might not work for Oracle, I found code snippet below work for Oracle:

以上答案可能不适用于 Oracle,我发现以下代码片段适用于 Oracle:

import cx_Oracle
def checkTableExists(dbcon, tablename):
    dbcur = dbcon.cursor()
    try:
        dbcur.execute("SELECT * FROM {}".format(tablename))
        return True
    except cx_Oracle.DatabaseError as e:
        x = e.args[0]
        if x.code == 942: ## Only catch ORA-00942: table or view does not exist error
            return False
        else:
            raise e
    finally:
        dbcur.close()