Python Curs出错

2024-04-19 17:34:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了一个脚本,直接用python cursor对象插入DB

 cursor.execute("INSERT INTO info ([height], [weight],[type]) VALUES (%s,%s,%s)" % (height, manufacturerid, weight)) 

有时我没有“重量”的数字,它会抛出一个错误:

Incorrect syntax near ','. (102) (SQLExecDirectW)")

你如何处理这样的错误?你知道吗


Tags: 对象info脚本executedbtype错误cursor
3条回答

使用try,除了查看python文档:https://docs.python.org/2/tutorial/errors.html

根据文档,您不应该这样做查询(您的方式):

cursor.execute("INSERT INTO info ([height], [weight],[type]) VALUES (%s,%s,%s)" % (height, manufacturerid, weight))

您应该按照以下步骤进行:

cursor.execute("INSERT INTO info ([height], [weight],[type]) VALUES (%s,%s,%s)" , (height, manufacturerid, weight))

查看this以获取更多帮助。你知道吗

您不应该对sql查询使用字符串格式。让它在更合适的层次上处理:

而不是:

cursor.execute("INSERT INTO info ([height], [weight], [type]) VALUES (%s,%s,%s)" %(height, manufacturerid, weight))

使用

cursor.execute("INSERT INTO info ([height], [weight], [type]) VALUES (%s,%s,%s)", (height, manufacturerid, weight))

将很可能解决您的问题,而不是受制于sql注入或像您所遇到的问题。你知道吗

由于这似乎是Oracle,而且我没有将其与Python一起使用,请参阅文档,但pep249指出参数化查询的占位符是: https://www.python.org/dev/peps/pep-0249/#paramstyle

相关问题 更多 >