You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python操作SQLite数据库插入数据时遇语法错误求助

Python SQLite插入数据报错:near ",": syntax error 解决方法

错误原因分析

  • INSERT语句语法错误:你的SQL插入语句中,字段列表的右括号后多了一个逗号,导致语法解析失败。原错误语句:
    self.sql = 'INSERT INTO CUSTOMERS(CustomerID, Customer_Name), values(?,?)'
    
    这里的, values是非法写法,正确格式应该去掉逗号,直接衔接VALUES关键字。
  • 主键未配置自增:CustomerID被设为主键,但未开启自增属性,插入时仅提供Customer_Name会因缺少主键值触发约束错误。

修正步骤

  1. 修复INSERT语句:由于CustomerID作为主键应自动生成,插入时无需指定该字段,仅需插入Customer_Name即可,修正后的SQL语句:
    self.sql = 'INSERT INTO CUSTOMERS(Customer_Name) VALUES(?)'
    
  2. 修改表结构,开启主键自增:创建CUSTOMERS表时,将CustomerID改为INTEGER PRIMARY KEY AUTOINCREMENT,让SQLite自动为新记录生成唯一ID:
    tables = {"CUSTOMERS": '''CustomerID INTEGER PRIMARY KEY AUTOINCREMENT,
        Customer_Name text'''}
    
  3. 数据元组无需调整:保持原有的(Customer_Name,)即可,因为现在仅需传入一个字段值。

完整修正代码

import sqlite3


class create_db:
    def __init__(self):
        self.conn = sqlite3.connect("EXAMPLE.db")
        self.c = self.conn.cursor()

    def create_tables(self, Tables):
        for table_name, field in Tables.items():
            self.c.execute(f'CREATE TABLE IF NOT EXISTS {table_name}({field})')
            self.conn.commit()


class customer_table(create_db):
    def __init__(self):
        super().__init__()

    def data_entry(self, Customer_Name):
        self.data_tuple = (Customer_Name,)
        self.sql = 'INSERT INTO CUSTOMERS(Customer_Name) VALUES(?)'
        self.c.execute(self.sql, self.data_tuple)
        self.conn.commit()


def main():
    db = create_db()
    tables = {"CUSTOMERS": '''CustomerID INTEGER PRIMARY KEY AUTOINCREMENT,
        Customer_Name text'''}

    db.create_tables(tables)
    customer = customer_table()
    customer.data_entry("Charlie")


main()

额外优化建议

  • 使用f-string拼接SQL语句比字符串相加更简洁易读(注意:若涉及用户输入内容,请勿直接拼接,需用参数化查询避免注入风险)。
  • 可添加异常处理逻辑,捕获数据库操作中的错误,提升调试效率。

内容的提问来源于stack exchange,提问作者charlie s

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 06:15:46