MySQLDb inserting data into a MySQL table with variables

Of the many ways to inset values into a MySQL database, we could use the below also:
insert_query = “INSERT INTO %s(symbol,
date,open,high,low,close,volume)
VALUES( %s,%s, %s , %s , %s , %s, %s )”
insert_cursor.execute(insert_query
%(symbol_Nasdaq,
symbol_Nasdaq,
row_Nasdaq[0],
row_Nasdaq[1],
row_Nasdaq[2],
row_Nasdaq[3],
row_Nasdaq[4],
volume_fin))
The above query will most likely give you an error stating the MySQL statement was not able to find a column name.
What actually happens is it translates one of your variables into a column by mistake or I am not sure about how this happens, but anyways the below query would definitely work.
insert_query = “INSERT INTO %s(symbol,
date,open,high,low,close,volume)
VALUES( ‘%s’,’%s’,’%s’,’%s’,’%s’,’%s’,’%s’)”
insert_cursor.execute(insert_query
%(symbol_Nasdaq,
symbol_Nasdaq,
row_Nasdaq[0],
row_Nasdaq[1],
row_Nasdaq[2],
row_Nasdaq[3],
row_Nasdaq[4],
volume_fin))
I just added a apostrophe for each variable. This correctly entered the data into my tables.

Leave a Reply

Your email address will not be published. Required fields are marked *