【问题标题】:Python SQL Update Syntax IssuesPython SQL 更新语法问题
【发布时间】:2018-09-10 14:48:06
【问题描述】:

您好,我关注 Python MYSQL update statement 并设法为我的程序的 SQL 更新生成此代码,其中包含变量函数:

def editInfo(start, userName):
    newFavGenre = input("Enter your favourite genre")
    newFavArtist = input("Enter your favourite artist")
    ## userName is a global variable
    con = lite.connect(db)
    cur = con.cursor()
    cur.execute ("""
    UPDATE users
    SET favGenre=%s, favArtist=%s
    WHERE username=%s
""", (newFavGenre, newFavArtist, userName))
    results = cur.fetchall()
    return result
    mainmenu()

并继续遇到此错误代码:

sqlite3.OperationalError: near "%": syntax error

任何想法我哪里出错了?

【问题讨论】:

    标签: python sqlite sql-parametrized-query


    【解决方案1】:

    您正在查看的帖子似乎是针对 MySQL 的,根据您的错误,我推测您正在使用 sqlite3 python 接口。

    看着sqlite3 docs...

    cur.execute("""
        UPDATE users
        SET favGenre=%s, favArtist=%s
        WHERE username=%s
    """, (newFavGenre, newFavArtist, userName))
    

    应该是

    cur.execute("""
        UPDATE users
        SET favGenre=?, favArtist=?
        WHERE username=?
        """, (newFavGenre, newFavArtist, userName))
    

    您也可以使用他们的命名样式,而不是使用一个元组,而是使用一个字典。

    cur.execute("""
        UPDATE users
        SET favGenre=:genre, favArtist=:artist
        WHERE username=:username
    """, {'genre':newFavGenre, 'artist': newFavArtist, 'username':userName})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-31
      • 1970-01-01
      相关资源
      最近更新 更多