简体   繁体   中英

how do I insert a row to a MySQL table in Python?

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")

By surrounding the statement in triple quotes, you're ensuring that the single quote after "into" does not close the string. That means that the whole text is treated as one literal string, which is why you're seeing that in the error message.

There's no reason to use triple quotes here at all. Just use normal single quotes throughout:

cursor.execute('INSERT INTO ' + table_name + ' (haiku_text, date_written) VALUES (%s, %s)', (haiku_text, date_written))

(Also note I've added a space before the opening paren of the column names.)

I believe you need a space after table name:

table_name + ' (haiku_text, date_written)
       -------^

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM