【问题标题】:How to get database name from postgres/mysql cursor object如何从 postgres/mysql 游标对象获取数据库名称
【发布时间】:2012-03-06 22:21:43
【问题描述】:

我有几个 postgres 和 mysql 游标对象暴露给我,它们是在某个宇宙中创建的。如何从这些游标对象中找到数据库名称(以及有关该数据库的其他信息)?

cursor.__dict__ 没有提供任何有用的信息。

【问题讨论】:

    标签: python mysql postgresql


    【解决方案1】:

    如果你也有连接(称之为 conn):

    conn.info.dbname
    

    【讨论】:

      【解决方案2】:

      对于 postgresql:-

      cursor.execute("select current_database()")
      db_name = cursor.fetchone()[0]
      

      【讨论】:

        【解决方案3】:

        我不了解 postgres,但使用 MySQLdb 你总是可以使用以下内容:

        cursor.execute("select database()")
        db_name = cursor.fetchone()[0]
        

        也许有一种更清洁的方法可以做到这一点......

        编辑:

        对于其他信息,这取决于您要查找的内容,例如获取表名

        cursor.execute("show tables")
        for r in cursor.fetchall():
            print r[0]
        

        还有许多其他功能可用...有什么特别需要的吗?

        【讨论】:

        • 如果光标附加到 PostgreSQL,这些都不起作用。
        • 是的,我知道...正如我所说,我对 PostgreSQL 了解不多。我猜总是可以使用一些东西,比如'SELECT table_name FROM information_schema.tables'。但我不知道有任何其他方法可以直接从光标获取此类信息:(。
        • @t00ny 感谢老兄的回答!我想出了一个类似的 postgres cursor_postgres.execute("select current_database()")
        • @jerrymouse 很高兴它适合您的需求!
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-29
        • 2021-03-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-30
        相关资源
        最近更新 更多