简体   繁体   English

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

[英]python - how to check if table exists?

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.任何帮助将不胜感激。

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. cursor.execute()是使用MySQLdb,Python MySQL驱动程序运行查询的方法。 You can pass two arguments, like: 您可以传递两个参数,例如:

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. 编辑:还有其他类似行为的Python驱动程序。 Look for yours :) 寻找你的:)

Use the "TABLES" information schema view. 使用“TABLES”信息架构视图。 http://dev.mysql.com/doc/refman/5.0/en/information-schema.html 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

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!')

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

I think the most straightforward way is using:我认为最直接的方法是使用:

SELECT COUNT(*) = 1 as exists FROM pg_tables WHERE tablename = 'my_table';

that returns if table exists:如果表存在则返回:

 exists 
--------
 t
(1 row)

or in Python using psycopg2 :或在 Python 中使用psycopg2

cur.execute(
    """
    SELECT COUNT(*) = 1 FROM pg_tables WHERE tablename = 'my_table';
    """
)
exists = cur.fetchone()[0]
print(exists)
True
if exists is False:
   # table does not exist
   ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM