首頁  >  文章  >  資料庫  >  如何解決MySQL資料插入語法錯誤?

如何解決MySQL資料插入語法錯誤?

Mary-Kate Olsen
Mary-Kate Olsen原創
2024-10-23 14:07:02886瀏覽

How to Resolve Syntax Error in MySQL Data Insertion?

將資料插入 MySQL 資料庫

目標是將整數 188 和 90 插入 MySQL 資料庫。但是,使用提供的程式碼的嘗試失敗了。

分析程式碼:

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

問題在於插入語句的語法。將資料插入表的正確語法是:

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

這是一個修改後的程式碼,示範如何成功插入資料:

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

或者,更全面的程式碼片段,涵蓋下面提供了使用佔位符建立表格並插入資料的方法:

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

使用此程式碼,您可以建立anooog1 表並將其有效地向其中插入資料。

以上是如何解決MySQL資料插入語法錯誤?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn