I've created a table with a name defined by a variable, and have then processed some text that I would like to insert into the table. I'm having a tough time finding the correct syntax, even when following this StackOverflow example. Here is a snippet of the code:
# Open database connection
db = MySQLdb.connect("localhost","root","menagerie","haiku_archive" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Create table using execute() method.
sql = "CREATE TABLE IF NOT EXISTS " + table_name + """
(haiku_text VARCHAR(120),
date_written CHAR(22))"""
cursor.execute(sql)
.
.
# SQL query to INSERT a haiku into the selected table
cursor.execute('''INSERT into ' + table_name + '(haiku_text, date_written) values (%s, %s)''', (haiku_text, date_written))
# Commit your changes in the database
db.commit()
# disconnect from server
db.close()
I'm deliberately not including the processing, which basically involves opening a text file and doing assorted strips, rstrips, joins, etc., to edit the text into the desired format before inserting into the table. I can include it if it would be helpful.
The error I'm getting isn't particularly helpful - at least to me:
_mysql_exceptions.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 '' + table_name + '(haiku_text, date_written) values ('the old pond<br>a frog ' at line 1")