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

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

Patricia Arquette
Release: 2024-11-27 16:54:10
Original
951 people have browsed it

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

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

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

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

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!

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