Python sqlite select where variable

To execute a SELECT statement in Python using SQLite with a variable in the WHERE clause, you can follow these steps:

1. Import the required modules:

    
    import sqlite3
    
    

2. Establish a connection to the SQLite database file:

    
    conn = sqlite3.connect('your_database.db')
    
    

3. Create a cursor object to interact with the database:

    
    cursor = conn.cursor()
    
    

4. Define a variable to hold the value for the WHERE clause:

    
    your_variable = 123
    
    

5. Execute the SELECT statement with the variable in the WHERE clause:

    
    cursor.execute("SELECT * FROM your_table WHERE column_name = ?", (your_variable,))
    
    

Note the use of the question mark (?) as a placeholder for the variable value. This is a safe way to prevent SQL injection attacks.

6. Fetch the results returned by the SELECT statement:

    
    results = cursor.fetchall()
    
    

7. Iterate over the results and process them as needed:

    
    for row in results:
        # Access the columns of each row
        column_value = row[0]
        # Process the retrieved data
    
    

8. Close the cursor and the connection to the database:

    
    cursor.close()
    conn.close()
    
    

Here’s an example for further clarification:

    
    import sqlite3

    conn = sqlite3.connect('example.db')
    cursor = conn.cursor()

    your_variable = 'John Doe'
    cursor.execute("SELECT * FROM users WHERE name = ?", (your_variable,))

    results = cursor.fetchall()
    for row in results:
        print("ID:", row[0])
        print("Name:", row[1])
        print("Email:", row[2])

    cursor.close()
    conn.close()
    
    

In this example, we assume there is a database file named ‘example.db’ with a table called ‘users’ containing columns: ID, name, and email. We are selecting all rows where the ‘name’ column matches the value stored in the ‘your_variable’ variable.

Leave a comment