I am trying to create a function that populates a MySQL table.
The function receives several variables as inputs:
Symbol
Var_Date
Stat_Name
Stat_Value
The value of Stat_Name changes as the code runs, eg Enterprise_Value, Profit_Margin, EBITDA - these are the column names within the table.
Stat_Value is the data that goes into the rows.
This code requires one Column Name as a variable, and three values as variables.
I found this previous article which looks promising, but I haven't been able to make it work as of yet.
dynamic mysql insert statement in python
I have pasted my attempt at the code below:
dbname = "mydb"
var_table = "exc"
symbol = 'ABC'
var_date = '20200629'
stat_name = 'Enterprise_Value'
stat_value = '12345'
def funPopulateTables(symbol, var_date, stat_name, stat_value):
conn = pymysql.connect(host="localhost", user="root", passwd=mypass, db=dbname)
my_cursor = conn.cursor()
query_placeholders = ', '.join(['%s'] * len(stat_value))
query_columns = ', '.join(stat_name)
add_word = ("INSERT INTO {table} " "(Symbol, Date, (%s)) " "VALUES (%s, %s, %s)") %(query_columns, query_placeholders)
data_word = (symbol, var_date, stat_value)
my_cursor.execute(add_word.format(table=var_table), data_word)
conn.commit()
conn.close()
funPopulateTables(symbol, var_date, stat_name, stat_value)
Any help would be greatly appreciated. Thanks in advance.