0

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!

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

The first code you gave is what I need, but it sets the variable to the value inside one or multiple sets of brackets. How do I get just the value into the variable?
@JasonMc92: the_variable = curs.execute("SELECT mycol FROM mytable").fetchone()[0]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.