CodeMouse92
CodeMouse92

Reputation: 6898

Loading SQLite3 values into Python variables

I have a project built in Python 2.7, using SQLite3 as the database. I need to know how to load an item from a particular row and column into an existing Python variable.

TY!

Upvotes: 0

Views: 1429

Answers (1)

mechanical_meat
mechanical_meat

Reputation: 169284

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.

Upvotes: 3

Related Questions