简体   繁体   English

Python:遍历MySQL列

[英]Python: Iterating through MySQL columns

I'm wondering if you can help me. 我想知道您是否能帮助我。 I'm trying to change the value in each column if the text matches a corresponding keyword. 如果文本与相应的关键字匹配,我试图更改每列中的值。 This is the loop: 这是循环:

for i in range(0, 20, 1):
    cur.execute("UPDATE table SET %s = 1 WHERE text rlike %s") %(column_names[i], search_terms[i])

The MySQL command works fine on its own, but not when I put it in the loop. MySQL命令本身可以正常运行,但是当我将其放入循环中时却无法正常运行。 It's giving an error at the first %s %s出现错误

Does anyone have any insights? 有人有见识吗?

This is the error: 这是错误:

_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s = 1 WHERE text rlike %s' at line 1")

Column names looks like 列名看起来像

column_names = ["col1","col2","col3"...]

Search terms look like 搜索字词看起来像

search_terms = ["'(^| |.|-)word1[;:,. ?-]'","'(^| |.|-)word2[;:,. ?-]'",...]

Missing quotes and wrong parenthesis placement... 引号缺失和括号位置错误...

for i in range(0, 20, 1):
    cur.execute("UPDATE table SET %s = 1 WHERE text rlike '%s'" %(column_names[i], search_terms[i]))
#                                                         ^  ^
#              (-----------------------------------------------------------------------------------)

Please note, this is not the right way of doing this, if your string may contain quotes by itself... 请注意, 如果您的字符串本身可能包含引号, 不是正确的方法...

What about that instead: 那呢:

for i in range(0, 20, 1):
    cur.execute("UPDATE table SET %s = 1 WHERE text rlike ?" % (column_names[i],),
                (search_terms[i],))

This uses the % operator to set the column name, but uses an executes parameter to bind the data, letting the DB driver escape all characters that need so. 这使用%运算符设置列名,但使用executes参数绑定数据,从而使DB驱动程序转义所有需要的字符。

The right way to do this is to give values to Python, which will quote things correctly. 正确的方法是给Python赋值,Python会正确引用事物。

adapted from voyager's post : 改编自航海家的职位

for i in range(0, 20, 1):
    cur.execute("UPDATE table SET {} = 1 WHERE text rlike %s".format(column_names[i]),
                (search_terms[i],),
               )

In this case it's confusing because the column_name isn't a value, it's part of the table structure, so it's inserted using good old string formatting. 在这种情况下,这是令人困惑的,因为column_name不是值,它是表结构的一部分,因此使用良好的旧字符串格式将其插入。 The search_term is a value, so is passed to cursor.execute() for correct, safe quoting. search_term是一个值,因此传递给cursor.execute()以获取正确,安全的引用。

(Don't use string manipulation to add the quotes -- you're exposing yourself to SQL injection.) (不要使用字符串操作来添加引号-您将自己暴露于SQL注入。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM