You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

SQLite INSERT INTO语法错误求助:插入代码触发near 'Exercise'报错

Fixing the sqlite3.OperationalError: near "Exercise": syntax error in Your Insert Statement

Hey there! That syntax error usually pops up when SQLite can’t parse the structure of your INSERT query correctly. Let’s break down the most likely causes and fixes for your Exercises table scenario:

Common Issues & Solutions

1. Missing Parentheses Around Column Names

This is the most frequent culprit. If you wrote your INSERT statement without wrapping the column list in parentheses, SQLite will get confused when it hits the Exercise column name.

❌ Wrong Syntax Example:

INSERT INTO Exercises Exercise, Weight, ID VALUES ('Bench Press', 80, 1);

SQLite sees Exercise right after the table name and doesn’t know what to do with it—hence the syntax error.

✅ Corrected Syntax:
Wrap your column names in parentheses to clearly define which fields you’re inserting into:

INSERT INTO Exercises (Exercise, Weight, ID) VALUES ('Bench Press', 80, 1);

2. Unescaped Column Names (Less Likely, But Possible)

While Exercise isn’t a reserved keyword in SQLite, if you’re using any names that clash with SQLite keywords or contain special characters, you’ll need to escape them. Use double quotes or square brackets around the column name:

INSERT INTO Exercises ("Exercise", "Weight", "ID") VALUES ('Deadlift', 100, 2);

3. Improper String Concatenation (If Using Python)

If you’re building your query with string formatting instead of parameterized queries, you might introduce syntax errors (and open yourself up to SQL injection).

❌ Bad Practice Example:

exercise = "Pull-up"
weight = 15
id = 3
cursor.execute(f"INSERT INTO Exercises (Exercise, Weight, ID) VALUES ('{exercise}', {weight}, {id})")

If exercise ever contains a single quote (like Joe's Push-up), this will break the query.

✅ Safe Parameterized Query:
Use SQLite’s built-in parameter binding with ? placeholders—this handles escaping automatically:

import sqlite3

conn = sqlite3.connect("your_database.db")
cursor = conn.cursor()

# Use ? as placeholders, pass values as a tuple
cursor.execute(
    "INSERT INTO Exercises (Exercise, Weight, ID) VALUES (?, ?, ?)",
    ("Pull-up", 15, 3)
)

conn.commit()
conn.close()

4. Typos or Mismatched Brackets

Double-check for:

  • Misspelled table/column names (e.g., Excercise instead of Exercise)
  • Missing commas between columns or values
  • Unclosed parentheses in your query

Quick Debug Tip

Print out the exact SQL query you’re trying to run before executing it. This will make it easy to spot syntax mistakes that your eye might miss in code.

内容的提问来源于stack exchange,提问作者Daniel Patrick

火山引擎 最新活动