Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Assuming the SQL query returns a single numeric value, here is one way to convert the output into an integer and store it in a variable:

import sqlite3 # or whatever database library you're using

# connect to the database and execute the query
conn = sqlite3.connect('example.db')
c = conn.cursor()
c.execute("SELECT COUNT(*) FROM my_table")

# fetch the result and convert it to an integer
result = c.fetchone()[0]
result = int(result)

# optionally store the value in a variable
my_count = result

This code connects to a SQLite database, executes a SELECT statement that counts the number of rows in a table, retrieves the result using the fetchone() method, extracts the first (and only) element of the result tuple, converts it to an integer using the int() function, and stores it in the variable result. You can of course replace the SQL query and database library with whatever you're using in your code.