Home >Database >Mysql Tutorial >How to Resolve Syntax Error in MySQL Data Insertion?

How to Resolve Syntax Error in MySQL Data Insertion?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-23 14:07:02946browse

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>

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>

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>

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>

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!

Statement:
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