ValueError:操作参数必须为str

时间:2017-01-23 13:30:33

标签: python sqlite sql-update python-db-api

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

ValueError:操作参数必须为str

以下是我的代码。我很想知道如何更新sqlite db中的多个列。

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()

2 个答案:

答案 0 :(得分: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()

请参阅https://realm.io/docs/swift/latest/#writes

答案 1 :(得分:-1)

如果你正在使用flask,你需要做的就是更新多个字段,实例化数据库类并提交会话(会话将节省你的时间,检查它们here

E.g。您的数据库类名称为Events,字段为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,只需从sessionmakersqlalchemy.orm导入create_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()