0

我正在将我的大脑从 PHP + MySQL 转移到 Python,目前我正在使用 sqlite 作为稍后其他东西的中介,因为它是内置的。

当我尝试设置要使用的初始数据库时,它会在多行的INSERT语句上引发错误:INSERT

import sqlite3

query = """CREATE TABLE IF NOT EXISTS "users" (
             "userID" INTEGER PRIMARY KEY autoincrement,
             "email" varchar(255) NOT NULL,
             "forename" varchar(50) NOT NULL,
             "surname" varchar(50) NOT NULL
           );
           INSERT INTO "users" ("userID", "email", "forename", "surname") 
           VALUES
             (1, 'user1@example.com', 'Test', 'User'),
             (2, 'user2@example.com', 'Test', 'User');"""

 db_conn = sqlite3.connect('test.db')
 try:
     db_conn.cursor().executescript(query)
     db_conn.commit()
 except:
     print "error with database"
     raise
 finally:
     db_conn.close()

当我运行它时,我得到:

error with database
Traceback (most recent call last):
  File "dbTest.py", line 20, in <module>
    db_conn.cursor().executescript(query)
sqlite2.OperationalError: near ",": syntax error

我花了很长时间才找到它不喜欢哪个“,”(我的意思是,真的吗?SQL 错误很糟糕!)。它确实是分隔INSERT行的“,”。

我做了什么傻事?

4

1 回答 1

1

For your insert I would use .executemany() instead of execute script, if you can. Otherwise if you can't, your INSERT statement will need to be seperate for each VALUES set you wish to pass it.

query = """INSERT INTO "users" ("userID", "email", "forename", "surname") 
           VALUES
           (?, ?, ?, ?)
        """
user_list = ((1, 'user1@example.com', 'Test', 'User'), (2, 'user2@example.com', 'Test', 'User'))
cursor.executemany("INSERT INTO myTable(data) values (?) ", user_list)

EDIT: According to this post, you can in fact have multiple value sets in a single INSERT statement, but the syntax is far from pretty.

于 2012-05-17T10:29:39.443 回答