How to Get a Row in SQLite with Python

I want to get the value of id where col1 = buhi and col2 = buhi.

Here is the Python code I came up with.

conn = sqlite3.connect('test.sqlite')
cur = conn.cursor()
params = ('buhi', 'buhi')
cur.execute('''SELECT id, col1, col2 FROM HOGE 
    WHERE col1 = ? AND col2 = ?''', params)
print(cur.fetchone())

cur.fetchone() returns the matching data in tuple.

(5, 'buhi', 'buhi')

So if you want to use any specific value, you can access it like…

cur.fetchone()[0]

Edit: If no row matches the SQL statement, fetchone() returns None, so it may be necessary to check if the data exists like the following.

row = cur.fetchone('''SELECT id, col1, col2 FROM HOGE 
    WHERE col1 = ? AND col2 = ?''', params)
if row is not None:
    print(row)

Author: admin

A software engineer in greater Seattle area

Leave a Reply

Your email address will not be published. Required fields are marked *