0

How can I send a parameter to a query this is my code

import pandas as pd
import sqlite3

def query_brand(filter):
    sql_query = pd.read_sql(f'SELECT * FROM ps_lss_brands WHERE label = {filter}', 
    self.conn_brand)
    df = pd.DataFrame(sql_query, columns = ['id_brand', 'label'])
    # print(df["id_brand"][0])
    print(df)
query_brand("ACURA")

This the error that I get:

pandas.errors.DatabaseError: Execution failed on sql 'SELECT * FROM ps_lss_brands WHERE label=ACURA': no such column: ACURA

My column is label but in the query it is trying to look for an ACURA column

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • Since ACURA is a string, the query need single-quotes around it. `f"SELECT * FROM ps_lss_brands WHERE label = '{filter}'"` Otherwise it assums ACURA is another column name. – John Gordon Jan 21 '23 at 03:48
  • thanks, it worked, could you put an answer and not as a comment, I can't select you as the best answer – Lucin Husein Jan 21 '23 at 03:58
  • [Related](https://stackoverflow.com/questions/902408/how-to-use-variables-in-sql-statement-in-python) - be aware that using f-strings for this can be dangerous with untrusted input. – snakecharmerb Jan 21 '23 at 07:32

1 Answers1

2

There is an issue in the fourth line. Please change your SQL query to include quotation marks around the {filter}

Specifically, make your fourth line something like this:

sql_query = pd.read_sql(f"SELECT * FROM ps_lss_brands WHERE label = '{filter}'", 
 self.conn_brand)

However, you should try to avoid this altogether, and instead use parameterized queries. This will prevent SQL injection.