问题
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.
回答1:
After following the advice from khelwood, this code is now working:
dbname = "mydb"
var_table = "exc"
var_date = '20200629'
symbol = 'AAB'
dict_stats = {'Enterprise_Value' : '12345', 'EBITDA' : '67890'}
def funPopulateTables(symbol, var_date, key, stat):
conn = pymysql.connect(host="localhost", user="root", passwd=mypass, db=dbname)
my_cursor = conn.cursor()
add_word_temp = str("INSERT INTO {table} " "(Symbol, Date, ") + key + str(") " " VALUES (%s, %s, %s)")
print(add_word_temp)
add_word = str(add_word_temp)
data_word = (symbol, var_date, stat)
my_cursor.execute(add_word.format(table=var_table), data_word)
conn.commit()
conn.close()
for key in dict_stats:
print(key)
stat = dict_stats[key]
print(stat)
funPopulateTables(symbol, var_date, key, stat)
来源:https://stackoverflow.com/questions/62638605/python-mysql-dynamic-insert-column-name-as-variable-values-as-variables