使用字典键值对更新 Python 中的查询

Update query in Python using Dictionary key Value pairs

我刚开始学习 python,我的要求是基于 Oracle Table 中的一个列,我正在使用字典键值对更新其他列。我的词典看起来像这样

{'United States': 'American', 'France': 'European', 'Great Britain': 'European'}

所以当国家列是美国时,描述列应该更新为美国,在我的数据库连接之后,这是我的代码

query = "select country from details_table "
        cursor.execute(query)
        returnrows = cursor.fetchone()
        while returnrows is not None:
                pickedvalue=returnrows[0]

               mainvalue=file_dictionary[pickedvalue]


                updatequery = "update details_table set description='%s' where country='%s'"

                cursor.execute(updatequery %(mainvalue,pickedvalue))
                returnrows = cursor.fetchone()

当我执行这个时我收到错误 "Not a query",所以我尝试更改引号我每次都收到不同的错误

updatequery = "update details_table set description=%s where country=%s"
updatequery = "update details_table set description='%s' where country=%s"

对于以上两个查询,我得到了 ORA-00933:SQL 命令未正确结束

updatequery = "update details_table set description=%s where country='%s'"

为此我得到了 ORA-00904: "AMERICAN": 无效标识符

有人能告诉我哪个是正确的查询吗,我什至像下面这样尝试过但没有成功

updatequery="update details_table set description={} where country='{}'"
sql=updatequery.format(main_value,pickedvalue)
cursor.execute(sql)

我不知道这是什么魔法,它开始使用这个,我不明白这段代码和上面的代码之间的逻辑区别是什么,有人请告诉我

 query = "select country from details_table"
        cursor.execute(query)
        returnrows = cursor.fetchall()
        for rows in returnrows:
            for pickedvalue in rows:
                requiredvalue = file_dictionary[pickedvalue]

                print(requiredvalue)
                updatequery = "update details_table set description='%s' where country='%s'"
                cursor.execute(updatequery % (requiredvalue, pickedvalue))

        connection.commit()

不要尝试使用字符串插值来更新您的查询!相反,请使用 documentation.

中注明的绑定变量

您的示例如下所示:

query = "select country from details_table"
cursor.execute(query)
returnrows = cursor.fetchall()
for rows in returnrows:
    for pickedvalue in rows:
        requiredvalue = file_dictionary[pickedvalue]

        print(requiredvalue)
        updatequery = "update details_table set description=:1 where country=:2"
        cursor.execute(updatequery, [requiredvalue, pickedvalue])

        connection.commit()

使用游标迭代和元组拆包的另一种方法如下:

query = "select country from details_table"
cursor.execute(query)
updateCursor = connection.cursor()
for country, in cursor:
    requiredvalue = file_dictionary[country]

    print(requiredvalue)
    updatequery = "update details_table set description=:1 where country=:2"
    updateCursor.execute(updatequery, [requiredvalue, pickedvalue])

    connection.commit()