Python Forum

Full Version: Mysql CREATE TABLE IF NOT EXISTS dynamic table name
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi folks, need some help here. I am trying to create a table in mysql from python and I get a syntax error while my print command shows the correct syntax. Any help is much appreciated.
symbol="TSLA"
option_date_head="2020-04-24"
create_table_sql = ("""CREATE TABLE IF NOT EXISTS """ + symbol + "-" + option_date_head + """ (option_expiry_date date, call_ask float, strikeprice int, put_ask float);""")
                print(create_table_sql)
                mycursor.execute(create_table_sql)
This is the print command output

CREATE TABLE IF NOT EXISTS TSLA-2020-05-01 (option_expiry_date date, call_ask float, strikeprice int, put_ask float);
And this is the error

Error:
_mysql_connector.MySQLInterfaceError: 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 '-2020-05-01 (option_expiry_date date, call_ask float, strikeprice int, put_ask f' at line 1
Figured it. Minor change was required

It required backticks for the tablename

create_table_sql = ("""CREATE TABLE IF NOT EXISTS `""" + symbol + "-" + option_date_head + """` (option_expiry_date date, call_ask float, strikeprice int, put_ask float);""")
For some reason Backticks are not displayed in the above command. I had a backtick before """ + symbol and one after option_date_head + """