简体   繁体   中英

Python SQLite3 Retrieve Variables From SELECT Query

I'm busy writting a python script that is querying two db tables to build a single row of data per row it finds. Here is my script at the moment

#========================================================================
# DB CONNECT FUNCTION
#========================================================================
def f_connect(status):

    global gv_conn
    global gv_curs

    if status == 1:
        gv_conn = sqlite3.connect("./data.db")
        gv_curs = gv_conn.cursor()
    else
        gv_conn.close()

#========================================================================
# PREPARE SQL STATEMENTS
#========================================================================
def f_statements():

    global users_stmt
    users_stmt = ("select * from users")
    global users_curs
    users_curs = gv_conn.cursor()

    global uinfo_stmt
    uinfo_stmt = ("select * from uinfo" +
                  "where ui_u_id = ?")
    global uinfo_curs
    uinfo_curs = gv_conn.cursor()

#========================================================================
#
# MAIN SCRIPT START
#
#========================================================================

f_connect(1)

f_statements()

la_users = []

for u_row in users_curs.execute(users_stmt):

    # THIS LINE GETS USERS FROM THE ABOVE STATEMENT
    # AND ADDS THEM TO THE DICTIONARY
    la_users.append({"u_id": u_row[0], "u_name": u_row[1]})

    # THIS LINE EXECUTES ANOTHER QUERY TO RETRIEVE
    # A SINGLE ROW OF DATA FROM ANOTHER TABLE
    la_uinfo = uinfo_curs.execute(uinfo_stmt, "1")

f_connect(0)

My problem is that when I execute the first sql statement I can get get the data by looping using a for loop which is storing the data so i can access it using u_row[int].

When I execute the second query it is storing it inside la_uinfo although when I try to get the data from la_uinfo[int] it doesn't work? How can I retrieve the data from my second query without using another for loop? (I shouldn't have to considering it only returns one row)

Cursors are not indexable, so cursor[0] will not work. To retrieve the first row of a cursor, you should use cursor.fetchone() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM