Python Forum
Mysql CREATE TABLE IF NOT EXISTS dynamic table name
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Mysql CREATE TABLE IF NOT EXISTS dynamic table name
#1
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 + """
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  drawing a table with the status of tasks in each thread pyfoo 3 404 Mar-01-2024, 09:29 AM
Last Post: nerdyaks
  How to create a table with different sizes of columns in MS word pepe 8 1,542 Dec-08-2023, 07:31 PM
Last Post: Pedroski55
  Trying to get counts/sum/percentages from pandas similar to pivot table cubangt 6 1,381 Oct-06-2023, 04:32 PM
Last Post: cubangt
  Mysql and mysql.connector error lostintime 2 660 Oct-03-2023, 10:25 PM
Last Post: lostintime
  dict table kucingkembar 4 718 Sep-30-2023, 03:53 PM
Last Post: deanhystad
  Going through HTML table with selenium emont 3 797 Sep-30-2023, 02:13 AM
Last Post: emont
Thumbs Up Convert word into pdf and copy table to outlook body in a prescribed format email2kmahe 1 742 Sep-22-2023, 02:33 PM
Last Post: carecavoador
  Using pyodbc&pandas to load a Table data to df tester_V 3 792 Sep-09-2023, 08:55 PM
Last Post: tester_V
  Find a string from a column of one table in another table visedwings049 8 1,164 Sep-07-2023, 03:22 PM
Last Post: deanhystad
Question Using SQLAlchemy, prevent SQLite3 table update by multiple program instances Calab 3 743 Aug-09-2023, 05:51 PM
Last Post: Calab

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020