Inserting Data into a MySQL Database: Resolved Issue
In an attempt to add the integers 188 and 90 to a MySQL database, a user encountered an error using the following code:
import MySQLdb conn = MySQLdb.connect(host= "localhost", user="root", passwd="newpassword", db="engy1") x = conn.cursor() x.execute("SELECT * FROM anooog1") x.execute (" INSERT INTO anooog1 VALUES ('%s','%s') ", (188,90)) row = x.fetchall()
Solution:
The error lies in the incorrect syntax used for the "INSERT" statement. The correct syntax in MySQL for inserting data is:
INSERT INTO table_name (column1, column2, ...) VALUES (value1, value2, ...)
In this case, the code should be modified to:
import MySQLdb conn = MySQLdb.connect(host= "localhost", user="root", passwd="newpassword", db="engy1") cursor = conn.cursor() try: cursor.execute("INSERT INTO anooog1 (COL1, COL2) VALUES (%s, %s)", (188, 90)) conn.commit() except: conn.rollback() conn.close()
This updated code uses the correct "INSERT" syntax and should successfully insert the integers into the "anooog1" table.
The above is the detailed content of Why Does My MySQL INSERT Statement Fail, and How Can I Fix It?. For more information, please follow other related articles on the PHP Chinese website!