2013-05-08 101 views
2

我收到以下错误:Python的SQL ValueError异常

query=query%db.literal(args) 
ValueError: Unsupported Format character 'P' (0x50) 

这里是我的查询中,从蟒蛇执行(注意phraseList是一个列表)

for elem in phraseList: 
    cursor.execute("""SELECT PHRASE,COUNT(CASEID) FROM TEST.NER WHERE LABEL LIKE '%PART%' \ 
    AND CASEID IN (SELECT DISTINCT CASEID FROM TEST.NER WHERE LABEL LIKE '%CONDITION%'\ 
    AND PHRASE LIKEPHRASE LIKE %s""",(elem,)) 

回答

2

MySQLdb重载Python字符串格式化语法和%P部分%PART%被视为字符串格式化表达式。

为了防止这种情况,你需要的字符一倍至%%

for elem in phraseList: 
    cursor.execute("""SELECT PHRASE,COUNT(CASEID) FROM TEST.NER WHERE LABEL LIKE '%%PART%%' \ 
    AND CASEID IN (SELECT DISTINCT CASEID FROM TEST.NER WHERE LABEL LIKE '%%CONDITION%%'\ 
    AND PHRASE LIKEPHRASE LIKE %s""",(elem,)) 
0

这里是什么让错误消失:

for elem in phraseList: 
    part='%part%' 
    condition='%condition%' 
    query="SELECT PHRASE,COUNT(CASEID) FROM TEST.NER WHERE LABEL LIKE %s \ 
    AND CASEID IN (SELECT DISTINCT CASEID FROM TEST.NER WHERE LABEL LIKE %s \ 
    AND PHRASE LIKE %s)" 
    params=(part,condition,elem) 
    cursor.execute(query,params) 
+0

现在'part'和'condition'插值没有''%通配符和已经小写。尽管使用它们作为SQL参数会对此有所帮助,但如果您改变含义,则这不起作用。 – 2013-05-08 08:40:20

+0

@Martjin:实际上现在它甚至可以与上面的part ='%part%'一起工作 – Yavar 2013-05-08 08:52:20

+0

您仍然匹配小写文本而不是大写。意思是不同于原来的。 – 2013-05-08 09:03:24