开发者

Loading SQLite3 values into Python variables

I have a project built in Python 2.7, using SQLite3 as the da开发者_JAVA技巧tabase. I need to know how to load an item from a particular row and column into an existing Python variable.

TY!


Here are the basic steps:

import sqlite3
conn = sqlite3.connect(':memory:')
curs = conn.cursor()
results = curs.execute( """SELECT mycol 
                             FROM mytable 
                            WHERE somecol = ?;""", (some_var,) ).fetchall()
curs.close()
conn.close()

For further research you can look into using a context manager (with statement), and how to fetch results into a dict. Here's an example:

with sqlite3.connect(':memory:') as conn:
    curs = conn.cursor()
    curs.row_factory = sqlite3.Row
    try:
        results = curs.execute( """SELECT mycol 
                                     FROM mytable 
                                    WHERE somecol = ?;""", 
                               (some_var,) ).fetchall()
    # you would put your exception-handling code here
    finally:
        curs.close()

The benefits of the context manager are many, including the fact that your connection is closed for you. The benefit of mapping the results in a dict is that you can access column values by name as opposed to a less-meaningful integer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜