【问题标题】:python - how to check if table exists?python - 如何检查表是否存在?
【发布时间】:2013-06-11 12:35:46
【问题描述】:

我正在使用这个功能:

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

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

这是我看到的:

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:

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

如何查看? 任何帮助将不胜感激。

【问题讨论】:

  • 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,)) 这很不安全,你应该改用绑定变量。
  • 恐怕这取决于您使用的数据库。使用 sqlite3,你可以做到SELECT * FROM sqlite_master WHERE type = 'table' AND name = 'the_table_name'
  • 您使用的是哪个数据库/驱动程序?你能提供更多信息吗?

标签: python sql


【解决方案1】:

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

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

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

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

【讨论】:

  • 不确定我是否理解(我第一次使用 python 和 sql)。当我使用时:MY_T=...-> 我正在创建表并将其保存在 MY_T 参数下,对吗?那么你的代码应该去哪里呢?什么是信息架构?如果没有 table_name 怎么办?(意味着它没有被创建) - 它应该返回什么?
  • 我建议让 cursor.execute() 函数进行替换,而不是自己使用 str.format() 进行替换
  • postgres 也有 information_schema.tables,这个解决方案适用于 postgres。
  • MSSQL 也有 information_schema.tables,此方案适用于 MSSQL
【解决方案2】:

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

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

cursor.execute(statement, parameters)

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

我认为你可以使用 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"

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

【讨论】:

    【解决方案3】:

    上面的答案可能不适用于 Oracle,我发现下面的代码 sn-p 适用于 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()
    

    【讨论】:

    • 与所有通过连接或格式化创建 SQL 语句的解决方案一样,表名应列入白名单,否则该解决方案存在 SQL 注入安全问题。
    【解决方案4】:

    我发现这适用于 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!')
    

    【讨论】:

      【解决方案5】:

      我认为最直接的方法是使用:

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

      如果表存在则返回:

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

      或者在 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
         ...
      

      【讨论】:

        猜你喜欢
        • 2017-05-31
        • 1970-01-01
        • 2019-11-25
        • 2013-04-07
        • 2017-07-18
        • 1970-01-01
        • 1970-01-01
        • 2017-04-01
        • 1970-01-01
        相关资源
        最近更新 更多