简体   繁体   English

从 Python 插入 SQLite DB - “接近”?“:语法错误”

[英]Insert Into SQLite DB from Python - “near ”?“: syntax error”

I keep receiving this error, while trying to insert data from Pandas df to SQLite DB: near "?": syntax error .我一直收到此错误,同时尝试将数据从 Pandas df 插入 SQLite DB: near "?": syntax error The code snippet looks like this, and in another script, similar idea works fine.代码片段看起来像这样,在另一个脚本中,类似的想法可以正常工作。 My df has 4 columns (int & 3x string), same column names and types are in SQLite table called titles .我的df有 4 列(int 和 3x 字符串),相同的列名和类型在 SQLite 表中,称为titles

conn = sqlite3.connect('test_db_2.db')
c = conn.cursor()

for i in range(len(df)):
    try:
        c.execute("""INSERT INTO titles (?,?,?,?)""",df.iloc[i,:])
        conn.commit()

What could be the cause?可能是什么原因?

You are missing the VALUES() keyword, which must precede the tuples of values that you want to insert:您缺少VALUES()关键字,该关键字必须位于要插入的值的元组之前:

INSERT INTO titles VALUES (?, ?, ?, ?)
                 --^--  

I would also recommend enumerating the columns that you want to insert.我还建议枚举要插入的列。 It is a good practice in SQL since it makes the query easier to understand to those that do not know your data structure, and can allow you to not provide values for all columns:这是 SQL 中的一个很好的做法,因为它使那些不知道您的数据结构的人更容易理解查询,并且可以允许您不为所有列提供值:

INSERT INTO titles(col1, col2, col3, col4) VALUES (?, ?, ?, ?)
                --^ -- changae this to your actual column names

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM