I have this query, it works great and does exactly what I want it to do. Pull stock data for companies given the users input, symbols
:
stock_info = {}
for stock in symbols:
stock_info[stock] = get_dict_resultset("SELECT
date, close
FROM security_price
WHERE
security_price.id=%s;", [stock])
get_dict_resultset()
connects to my postgreSQL db, pulls data, and stores it into a python dictionary. Here is the definition:
def get_dict_resultset(query, param):
cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
cur.execute(query, param)
ans =cur.fetchall()
dict_result = []
for row in ans:
dict_result.append(dict(row))
return dict_result
What I don't like about my query, is the for loop that it's nested in. I want to limit the amount of transactions happening with my database and the user. Given the amount of values in symbols
, it seems a bit silly having it in a for loop and iterating the same calls to the dB when I could just use one simple statement.
I've tried playing around with executemany and execute_batch, but struggling to implement that into my code above. How can I structure my query without using a for-loop? I've already sanitized my inputs, just trying to implement this one last step!