I am using python, pymysql and MYSQL. This code looks for an existing row with data in it. Eg, Symbol = AGL, Date = 20200629, Enterprise_Value = 12345.
If I find an existing row, I want to update it. The code cycles through variables called stat_name and stats.
Stat_Name holds the column names and stats are the data values that will be stored in the rows.
The SELECT COUNT portion of the code works. However, when it gets to the UPDATE {table} section, it errors out with this message:
pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax
to use near ''Enterprise_Value' = '12345' WHERE Symbol = 'AGL' AND Date = '20200629'' at line 1")
I've pasted the current version of the code below:
dbname = "mydb"
var_table = "asx"
var_date = '20200629'
symbol = 'AGL'
dict_stats = {'Enterprise_Value' : '12345', 'EBITDA' : '67890'}
def funPopulateTables(symbol, var_date, stat_name, stat):
conn = pymysql.connect(host="localhost", user="root", passwd=secret_line, db=dbname)
my_cursor = conn.cursor()
#Find whether the row already exists.
select_word_temp = ("SELECT COUNT(*) from {table} WHERE Symbol = %s AND Date = %s")
select_word = str(select_word_temp)
data_word = (symbol, var_date)
my_cursor.execute(select_word.format(table=var_table), data_word)
result = my_cursor.fetchone()
row_count = my_cursor.rowcount
print(result)
if row_count != 0:
#The looks to be a syntax problem in this area.
update_word_temp = ("UPDATE {table} SET %s = %s WHERE Symbol = %s AND Date = %s")
update_word = str(update_word_temp)
update_data_word = (stat_name, stat, symbol, var_date)
my_cursor.execute(update_word.format(table=var_table), update_data_word)
conn.commit()
conn.close()
for stat_name in dict_stats:
print(stat_name)
stat = dict_stats[stat_name]
print(stat)
funPopulateTables(symbol, var_date, stat_name, stat)
I found this article, which looks useful, but I haven't been able to get it to work using their suggested syntax as yet. Python MYSQL update statement
Any help would be greatly appreciated. Thanks in advance.