Home > Database > Mysql Tutorial > body text

How to Resolve Syntax Error in MySQL Data Insertion?

Mary-Kate Olsen
Release: 2024-10-23 14:07:02
Original
886 people have browsed it

How to Resolve Syntax Error in MySQL Data Insertion?

Inserting Data into MySQL Database

The goal is to insert the integers 188 and 90 into a MySQL database. However, attempts using the provided code have failed.

Analyzing the code:

<code class="python">conn.cursor()
x.execute("SELECT *  FROM anooog1")
x.execute (" INSERT INTO anooog1 VALUES ('%s','%s') ", (188,90))
row = x.fetchall()</code>
Copy after login

The issue lies in the syntax of the insert statement. The correct syntax for inserting data into a table is:

<code class="python">x.execute("INSERT INTO anooog1 VALUES (%s, %s)", (188, 90))</code>
Copy after login

Here's a modified code that demonstrates how to insert data successfully:

<code class="python">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()</code>
Copy after login

Alternatively, a more comprehensive code snippet that covers creating the table and inserting data using placeholders is provided below:

<code class="python">import MySQLdb

# Connect to database
db = MySQLdb.connect("localhost", "root", "password", "testdb")

# Setup cursor
cursor = db.cursor()

# Create anooog1 table
cursor.execute("DROP TABLE IF EXISTS anooog1")
sql = """CREATE TABLE anooog1 (
          COL1 INT,  
          COL2 INT )"""
cursor.execute(sql)

# Insert data into table
try:
    cursor.execute("""INSERT INTO anooog1 VALUES (%s, %s)""", (188, 90))
    db.commit()
except:
    db.rollback()

# Show table
cursor.execute("""SELECT * FROM anooog1;""")
print(cursor.fetchall())

# Close database connection
db.close()</code>
Copy after login

Using this code, you can create the anooog1 table and insert data into it efficiently.

The above is the detailed content of How to Resolve Syntax Error in MySQL Data Insertion?. For more information, please follow other related articles on the PHP Chinese website!

source:php
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!