Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving the result of a SQLite query as a Python variable

The problem I'm dealing with is, I want to save a sqlite3 query result in a variable, I created the following code:

import sqlite3
conn=sqlite3.connect('Database.db')
c=conn.cursor()
#this is implicit, but there is no xxx row in my table, condition and something 
#arent real parameters for my query
qry=("SELECT xxx FROM xxx WHERE condition=something")
y=c.execute(qry)
print(y)

when I run this code I get the following in the print:

<sqlite3.Cursor object at 0x01FCD6A0>

now, if for example I used a for cycle to print row in that query:

for row in c.execute(qry):
    print(row)

I would have no problem, but I want to save the value that the query prints in a variable, it should be noted that I am trying to save a query that has a single row and single column, ex: ('EXAMPLE',)

Is there a way I can save a single row, single column query in a variable and then print it? Should I install some module?

like image 728
Byron Mh Avatar asked Jan 06 '23 20:01

Byron Mh


1 Answers

use fetchone with index 0 [0]:

c.execute(qry)
y=c.fetchone()[0]
print(y)
like image 183
midori Avatar answered Jan 10 '23 06:01

midori