Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trying to use Python variable names in psycopg2 queries

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

You could use a placeholder for it:

cur.execute('SELECT company,stockTicker,industry FROM stockNames WHERE stockTicker = %s', (stockchoice,))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading