如何修复“)”处或附近的语法错误什么时候使用psycopg2?

发布于 2025-01-15 17:38:27 字数 592 浏览 2 评论 0原文

我正在编写两年前别人制作的剧本。同时,使用的数据库已从 mySQLdb 更改为 psycopg2,这导致了一些错误。错误之一是语法错误。

尝试执行查询时收到错误消息,指出“)”处或附近存在语法错误。代码如下:

list = []
format_strings = ",".join([%s]) + len(list)
db.execute("SELECT * FROM table WHERE column IN (%s,%s)", (format_strings, tuple(list)))
input = db.fetchall()

错误说syntaxerror is in the line: table WHERE column IN (' ', ())

最初代码是这样的:

db.execute("SELECT & FROM table WHERE column IN (%s)" % format_strings, tuple(list))

这也给出了语法错误,网上搜索后我把它改成了我提到的第一个代码。

我尝试了许多不同的尝试和错误,但没有任何效果。有谁知道如何解决这个问题?

I am working on a script that was made by someone else two years ago. In the meantime, the database used has changed from mySQLdb to psycopg2 which caused some errors. One of the error is a syntax error.

When trying to execute a query is get the error saying that there is a syntax error at or near ")". The code is as follows:

list = []
format_strings = ",".join([%s]) + len(list)
db.execute("SELECT * FROM table WHERE column IN (%s,%s)", (format_strings, tuple(list)))
input = db.fetchall()

The error says the syntaxerror is in the line: table WHERE column IN (' ', ())

Initially the code was as follows:

db.execute("SELECT & FROM table WHERE column IN (%s)" % format_strings, tuple(list))

This also gave the syntax error, and after searching online I changed it into the first code I mentioned.

I have tried many different trial and errors but nothing works. Does anyone know how to fix this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

圈圈圆圆圈圈 2025-01-22 17:38:27

Psycopg2 会自动将元组转换为适合的结构>IN 子句,因此您可以使用裸 %s 作为 IN 并传递包含元组中的值的单个元素列表或元组来生成所需的 SQL 语句。

>>> values = [1, 2, 3]
>>> # Output the statement that will be sent to the database
>>> db.mogrify("""select * from t where col in %s""" , [tuple(values)])
b'select * from t where col in (1, 2, 3)'

Psycopg2 will automatically convert a tuple to a structure suitable for an IN clause, so you can use a bare %s for the IN and pass a single element list or tuple containing the values within a tuple to generate the desired SQL statement.

>>> values = [1, 2, 3]
>>> # Output the statement that will be sent to the database
>>> db.mogrify("""select * from t where col in %s""" , [tuple(values)])
b'select * from t where col in (1, 2, 3)'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文