3

我正在尝试使用 python 函数将一些数据库字段更新到 SQLite DB。我不断收到以下错误:

ValueError: 操作参数必须是 str

下面是我的代码。我很想知道如何更新 sqlite 数据库中的多个列。

def updateEventData():
    ID = input('Enter ID of row you\'d like to update: ')
    eventname = input('\nPlease enter event name: ')
    startdate = input('\nPlease enter event start date: (DD/MM/YYYY): ')
    enddate = input('\nPlease enter event end date: (DD/MM/YYYY): ')
    venue = input('\nPlease enter event venue: ')

    # Sql update
    sql = """
    UPDATE event_details
    SET name, startdate, enddate, venue, (?, ?, ?, ?)
    WHERE ROWID = ?
    """, (eventname, startdate, enddate, venue, ID)
    c.execute(sql)
    conn.commit()
4

2 回答 2

5

您需要sql单独传递和参数,而不是作为包含sql和参数的元组:

sql = """
UPDATE event_details
SET name, startdate, enddate, venue, (?, ?, ?, ?)
WHERE ROWID = ?
"""
c.execute(sql, (eventname, startdate, enddate, venue, ID))
#         ^^^  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
#     separated argument, not as a single argument
conn.commit()

DB API 2 documentation, Cursor.execute(operation, parameter)

于 2017-01-23T13:31:21.493 回答
-1

如果您使用的是烧瓶,更新多个字段所需要做的就是实例化数据库类并提交会话(会话将为您节省大量时间,请在此处查看

例如,您的数据库类名称是事件,字段event_name, start_date, end_date and venue 与会话:

def updateEventData():
    ID = input('Enter ID of row you\'d like to update: ')
    eventname = input('\nPlease enter event name: ')
    startdate = input('\nPlease enter event start date: (DD/MM/YYYY): ')
    enddate = input('\nPlease enter event end date: (DD/MM/YYYY): ')
    venue = input('\nPlease enter event venue: ')

    events = Events(event_name=eventname, start_date=startdate, end_date=enddate, venue=venue)
    events.session.commit()

要实例化会话,您需要 sqlalchemy,只需导入sessionmakerfrom即可。完整代码:sqlalchemy.ormcreate_engine

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

class Foo(object):

    engine = create_engine('sqlite:///foo.sqlite', echo = False)

    # create new session object for queries
    Session = sessionmaker()
    Session.configure(bind=engine)
    session = Session()

    def updateEventData():
        ID = input('Enter ID of row you\'d like to update: ')
        eventname = input('\nPlease enter event name: ')
        startdate = input('\nPlease enter event start date: (DD/MM/YYYY): ')
        enddate = input('\nPlease enter event end date: (DD/MM/YYYY): ')
        venue = input('\nPlease enter event venue: ')

        events = Events(event_name=eventname, start_date=startdate, end_date=enddate, venue=venue)
        events.session.add(events)
        events.session.commit()
于 2017-01-23T14:07:59.660 回答