Home > Database > Mysql Tutorial > Why Does My Python MySQL INSERT Statement Fail, and How Can I Fix It?

Why Does My Python MySQL INSERT Statement Fail, and How Can I Fix It?

Mary-Kate Olsen
Release: 2024-12-09 14:57:12
Original
600 people have browsed it

Why Does My Python MySQL INSERT Statement Fail, and How Can I Fix It?

Inserting Data into a MySQL Database

Problem Statement

When attempting to insert the values 188 and 90 into a MySQL database using a Python script, the code fails to execute successfully. The following code snippet illustrates the unsuccessful attempt:

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()
Copy after login

Solution

The issue arises due to an error in the SQL query used for insertion. The correct syntax for inserting data into a MySQL table is as follows:

INSERT INTO table_name (column1, column2, ...) VALUES (value1, value2, ...)
Copy after login

In the provided code, the single quotes ('') around the values are incorrect. Removing them will allow the query to execute successfully.

Additionally, the exception handling mechanism has been added to prevent unexpected errors from rolling back changes made to the database. The modified code below demonstrates the correct implementation:

import MySQLdb
conn = MySQLdb.connect(host= "localhost",
                  user="root",
                  passwd="newpassword",
                  db="engy1")
x = conn.cursor()

try:
   x.execute("""INSERT INTO anooog1 VALUES (%s,%s)""",(188,90))
   conn.commit()
except:
   conn.rollback()

conn.close()
Copy after login

This revised code should successfully insert the values 188 and 90 into the specified MySQL table.

The above is the detailed content of Why Does My Python MySQL INSERT Statement Fail, and How Can I Fix It?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template