Python - mysqlDB,sqlite 结果作为字典

发布于 2024-10-01 10:51:30 字数 355 浏览 15 评论 0原文

当我做一些事情时,

sqlite.cursor.execute("SELECT * FROM foo")
result = sqlite.cursor.fetchone()

我认为必须记住列似乎能够取出它们的顺序,例如

result[0] is id
result[1] is first_name

有没有办法返回字典?所以我可以只使用 result['id'] 或类似的?

编号列的问题是,如果您编写代码然后插入一列,您可能必须更改代码,例如first_name的result[1]现在可能是date_joined,因此必须更新所有代码...

When I do someting like

sqlite.cursor.execute("SELECT * FROM foo")
result = sqlite.cursor.fetchone()

I think have to remember the order the columns appear to be able to fetch them out, eg

result[0] is id
result[1] is first_name

is there a way to return a dictionary? so I can instead just use result['id'] or similar?

The problem with the numbered columns is, if you write your code then insert a column you might have to change the code eg result[1] for first_name might now be a date_joined so would have to update all the code...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

南风几经秋 2024-10-08 10:51:30
import MySQLdb
dbConn = MySQLdb.connect(host='xyz', user='xyz', passwd='xyz', db='xyz')
dictCursor = dbConn.cursor(MySQLdb.cursors.DictCursor)
dictCursor.execute("SELECT a,b,c FROM table_xyz")
resultSet = dictCursor.fetchall()
for row in resultSet:
    print row['a']
dictCursor.close
dbConn.close()
import MySQLdb
dbConn = MySQLdb.connect(host='xyz', user='xyz', passwd='xyz', db='xyz')
dictCursor = dbConn.cursor(MySQLdb.cursors.DictCursor)
dictCursor.execute("SELECT a,b,c FROM table_xyz")
resultSet = dictCursor.fetchall()
for row in resultSet:
    print row['a']
dictCursor.close
dbConn.close()
听你说爱我 2024-10-08 10:51:30

在 mysqlDB 中执行此操作,只需将以下内容添加到 connect 函数调用中

cursorclass = MySQLdb.cursors.DictCursor

Doing this in mysqlDB you just add the following to the connect function call

cursorclass = MySQLdb.cursors.DictCursor
涫野音 2024-10-08 10:51:30

你可以很容易地做到这一点。对于 SQLite:my_connection.row_factory = sqlite3.Row

查看 python 文档:http://docs.python.org/library/sqlite3.html#accessing-columns-by-name-instead-of-by-index< /a>

更新:

Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29) 
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sqlite3
>>> conn = sqlite3.connect(':memory:')
>>> conn.row_factory = sqlite3.Row
>>> c = conn.cursor()
>>> c.execute('create table test (col1,col2)')
<sqlite3.Cursor object at 0x1004bb298>
>>> c.execute("insert into test values (1,'foo')")
<sqlite3.Cursor object at 0x1004bb298>
>>> c.execute("insert into test values (2,'bar')")
<sqlite3.Cursor object at 0x1004bb298>
>>> for i in c.execute('select * from test'): print i['col1'], i['col2']
... 
1 foo
2 bar

You can do this very easily. For SQLite: my_connection.row_factory = sqlite3.Row

Check it out on the python docs: http://docs.python.org/library/sqlite3.html#accessing-columns-by-name-instead-of-by-index

UPDATE:

Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29) 
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sqlite3
>>> conn = sqlite3.connect(':memory:')
>>> conn.row_factory = sqlite3.Row
>>> c = conn.cursor()
>>> c.execute('create table test (col1,col2)')
<sqlite3.Cursor object at 0x1004bb298>
>>> c.execute("insert into test values (1,'foo')")
<sqlite3.Cursor object at 0x1004bb298>
>>> c.execute("insert into test values (2,'bar')")
<sqlite3.Cursor object at 0x1004bb298>
>>> for i in c.execute('select * from test'): print i['col1'], i['col2']
... 
1 foo
2 bar
随风而去 2024-10-08 10:51:30

David Beazley 在他的 Python Essential Reference 中提供了一个很好的示例。
我手头没有这本书,但我认为他的例子是这样的:

def dict_gen(curs):
    ''' From Python Essential Reference by David Beazley
    '''
    import itertools
    field_names = [d[0].lower() for d in curs.description]
    while True:
        rows = curs.fetchmany()
        if not rows: return
        for row in rows:
            yield dict(itertools.izip(field_names, row))

示例用法:

>>> import sqlite3
>>> conn = sqlite3.connect(':memory:')
>>> c = conn.cursor()
>>> c.execute('create table test (col1,col2)')
<sqlite3.Cursor object at 0x011A96A0>
>>> c.execute("insert into test values (1,'foo')")
<sqlite3.Cursor object at 0x011A96A0>
>>> c.execute("insert into test values (2,'bar')")
<sqlite3.Cursor object at 0x011A96A0>
# `dict_gen` function code here
>>> [r for r in dict_gen(c.execute('select * from test'))]
[{'col2': u'foo', 'col1': 1}, {'col2': u'bar', 'col1': 2}]

David Beazley has a nice example of this in his Python Essential Reference.
I don't have the book at hand, but I think his example is something like this:

def dict_gen(curs):
    ''' From Python Essential Reference by David Beazley
    '''
    import itertools
    field_names = [d[0].lower() for d in curs.description]
    while True:
        rows = curs.fetchmany()
        if not rows: return
        for row in rows:
            yield dict(itertools.izip(field_names, row))

Sample usage:

>>> import sqlite3
>>> conn = sqlite3.connect(':memory:')
>>> c = conn.cursor()
>>> c.execute('create table test (col1,col2)')
<sqlite3.Cursor object at 0x011A96A0>
>>> c.execute("insert into test values (1,'foo')")
<sqlite3.Cursor object at 0x011A96A0>
>>> c.execute("insert into test values (2,'bar')")
<sqlite3.Cursor object at 0x011A96A0>
# `dict_gen` function code here
>>> [r for r in dict_gen(c.execute('select * from test'))]
[{'col2': u'foo', 'col1': 1}, {'col2': u'bar', 'col1': 2}]
往昔成烟 2024-10-08 10:51:30

sqlite3.Row 实例可以转换为 dict - 非常方便地将结果转储为 json

>>> csr = conn.cursor()
>>> csr.row_factory = sqlite3.Row
>>> csr.execute('select col1, col2 from test')
>>> json.dumps(dict(result=[dict(r) for r in csr.fetchall()]))

a sqlite3.Row instance can be converted to dict - very handy to dump a result as json

>>> csr = conn.cursor()
>>> csr.row_factory = sqlite3.Row
>>> csr.execute('select col1, col2 from test')
>>> json.dumps(dict(result=[dict(r) for r in csr.fetchall()]))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文