Trying to use Python variable names in psycopg2 queries

Question:

I am writing part of a Python program where I query a PostgreSQL table called stockNames and use the results to print information based on user input. stockNames has the following layout:

company     stockTicker     industry
Starbucks   SBUX            Food/Beverage
...

I also have a series of Python print statements as follows (brief variable assignments shown as well):

stockChoice = input('Select a stock ticker: ')
stockPrice=soup.find(class_="Fw(b) Fz(36px) Mb(-4px) D(ib)")

print('n' 'Company Name:')
print('Stock Ticker: ',stockChoice)
print('Industry: ' 'n')
print('n' 'Date: ',)
print('Stock Price: ',stockPrice.text) 

My goal is to query the company name and industry based on the stock ticker the user inputs (stored as stockChoice in the Python program but existing as stockTicker in the PostgreSQL table stockNames) and print that information in the print lines above. I tried including the stockChoice variable in the psycopg2 query, but received the following error:

cur.execute('SELECT company,stockTicker,industry FROM stockNames WHERE stockTicker=stockChoice;')

column "stockchoice" does not exist

The error makes sense since stockchoice isn’t a column in my original stockNames table, but I’m not sure how to navigate this issue. Any help would be appreciated.

Asked By: jon bon journo

||

Answers:

You could use a placeholder for it:

cur.execute('SELECT company,stockTicker,industry FROM stockNames WHERE stockTicker = %s', (stockchoice,))
Answered By: Mureinik
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.