【问题标题】:Get column name from a table's dataset in python从python中的表的数据集中获取列名
【发布时间】:2015-03-19 21:49:12
【问题描述】:

我正在尝试从表中获取列

 query = session.prepare("""  SELECT * FROM mytable   """)

 row_data = session.execute(query, )

我想要的是从 row_data 中获取列名。 有没有办法做到这一点。

【问题讨论】:

  • 您使用的是哪个 DB API?大多数 DB API 允许某种形式的“命名游标”
  • 好的 - 你使用哪个 python 库来访问它?
  • Cassandra'sown lib cassandra.cluster..有没有办法获取表元数据?

标签: python python-2.7 cassandra


【解决方案1】:

在大多数 python 数据库适配器中,您可以使用DictCursor 来检索记录,使用类似于 Python 字典的接口而不是元组。

使用 cassandra

>>> from cassandra.query import dict_factory
>>> session = cluster.connect('mykeyspace')
>>> session.row_factory = dict_factory
>>> rows = session.execute("SELECT name, age FROM users LIMIT 1")
>>> print rows[0]
{u'age': 42, u'name': u'Bob'}

使用 psycopg2

>>> dict_cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
>>> dict_cur.execute("INSERT INTO test (num, data) VALUES(%s, %s)",
...                  (100, "abc'def"))
>>> dict_cur.execute("SELECT * FROM test")
>>> rec = dict_cur.fetchone()
>>> rec['id']
1
>>> rec['num']
100
>>> rec['data']
"abc'def"

使用 MySQLdb

>>> import MySQLdb 
>>> import MySQLdb.cursors 
>>> myDb = MySQLdb.connect(user='andy47', passwd='password', db='db_name', cursorclass=MySQLdb.cursors.DictCursor) 
>>> myCurs = myDb.cursor() 
>>> myCurs.execute("SELECT columna, columnb FROM tablea") 
>>> firstRow = myCurs.fetchone() 
{'columna':'first value', 'columnb':'second value'}

【讨论】:

    【解决方案2】:

    你可以这样,

    fields = [ix[0] for ix in cursor.description]
    

    Documentation

    cursor.description # 最初没有,代表 N 个元组的列表 执行后一行中的 N 列。仅有的 包含类型和名称信息,而不是值。

    【讨论】:

      【解决方案3】:

      使用 cassandra-driver 3.14,您还可以通过访问查询结果条目的 _fields 参数来获取列名。

      from cassandra.cluster import Cluster
      
      session = Cluster().connect('mykeyspace')
      
      rows = session.execute('select * from mytable limit 1')
      
      column_names = rows.one()._fields
      

      【讨论】:

        猜你喜欢
        • 2015-01-11
        • 1970-01-01
        • 2014-05-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多