_mysql_exceptions.ProgrammingError 1064,"您的SQL语法中有错误;校验

时间:2018-02-25 12:41:39

标签: python mysql database python-3.x python-2.7

for toolx in tools:
    print toolx

output_count = """SELECT count(tool),count(""SELECT count(tool) FROM 
               core_data WHERE sentiment = 'positive' AND tool = '%s'"") 
               from core_data where tool = '%s'""" % (toolx, toolx)

在查询中运行多个sql语句时,我不知道如何与字符串进行比较。

1 个答案:

答案 0 :(得分:0)

您的代码存在几个问题。

首先,您应该使用占位符作为参数,并在执行SQL查询时将参数作为元组传递给cursor。这样MySQL就可以在一定程度上防范SQL注入攻击。

示例:

cursor.execute("SELECT * FROM core_data WHERE sentiment = 'positive' AND tool = %s",  (toolx,))

第二个问题是当你计算所有积极的情绪时。你会更好:

SELECT count(*) as 'All count', 
       sum(case when sentiment = 'positive' then 1 else 0 end) as 'Positive Sentiments'
FROM core_data 
WHERE tool = %s

总结一下,以下是它的外观:

for toolx in tools:
    print toolx
    query = "SELECT count(*) as 'All count', sum(case when sentiment = 'positive' then 1 else 0 end) as 'Positive Sentiments' FROM core_data WHERE tool = %s"
    results = cursor.execute(query, (toolx,))
    # and then you do the fetchone and take counts