简体   繁体   English

使用pygresql(pg模块)执行SQL select in语句

[英]Execute SQL select in statement using pygresql(pg module)

I am working on a python script to connect to postgress databases using pygresql module. 我正在使用python脚本使用pygresql模块连接到postgress数据库。 Below is the code 下面是代码

I am trying to run the query by passing tuple as parameter. 我试图通过传递元组作为参数来运行查询。 query looks like this: 查询看起来像这样:

select sum(column1) from table_name where column2 in %s,(tuple,).

But I keep getting error "ERROR: syntax error at or near "%"". 但是我不断收到错误“ ERROR:语法错误在或接近“%””。

import pg
tup_ids=('a','b','c')
def connection(cs):   
  """
      :param cs: cs is connection string
      :return:
       """
      conn=pg.connect(cs)
      return conn
conn1 = connection(conn_string)
conn1.query('select sum(column1) from table_name where column2 in %s',(tup_ids,).

I am able to execute query using psycopg2 module. 我可以使用psycopg2模块执行查询。 I am not able to pass tuple parameter for pg module. 我无法为pg模块传递元组参数。 I have been pgresql documentation. 我一直是pgresql文档。 I am not sure where I am doing wrong. 我不确定我在哪里做错了。

FYI: I need to use pygresql module only. 仅供参考:我只需要使用pygresql模块。 Please help. 请帮忙。

PyGreSQL "classic" (the pg module) supports PostgreSQL native parameters in its query method, labelled $1 , $2 , ... Unfortunately, these accept only individual values, so you must construct a parameter list with as many values as your tuple first. PyGreSQL“经典”(pg模块)在其query方法中支持PostgreSQL本机参数,标记为$1$2 ,...。不幸的是,它们仅接受单个值,因此您必须首先构造一个与元组一样多的值的参数列表。 This is very simple, though: 不过,这很简单:

con = pg.connect(cs)
p_list = ','.join('$%d' % n for n in range(1, len(tup_ids) + 1))
q = con.query('select sum(column1) from table_name where column2 in (%s)' % p_list, tup_ids)
print(q.getresult())

Alternatively, you can use the query_formatted method available in the DB wrapper class of PyGreSQL classic (it is recommended to use that wrapper instead of raw connections anyway, because it adds a lot of convenience methods). 另外,您可以使用PyGreSQL经典DB包装器类中可用的query_formatted方法(无论如何,建议使用该包装器而不是原始连接,因为它增加了许多便利方法)。 This method uses Python formatting, so it must be used like this: 此方法使用Python格式,因此必须这样使用:

db = pg.DB(cs)
p_list = ','.join(['%s'] * len(tup_ids))
q = db.query_formatted(
    'select sum(column1) from table_name where column2 in (%s)' % p_list, tup_ids)
print(q.getresult())

By using ANY instead of IN in your SQL statement, you can avoid creating a parameter list, and pass the values as a single list: 通过在SQL语句中使用ANY而不是IN ,可以避免创建参数列表,并将值作为单个列表传递:

db = pg.DB(cs)
q = db.query_formatted(
    'select sum(column1) from table_name where column2 = any(%s)', [list(tup_ids)])
print(q.getresult())

The PyGreSQL DB API 2 module (pgdb) also uses Python formatting and works similarly: PyGreSQL DB API 2模块(pgdb)也使用Python格式,并且工作类似:

con = pgdb.connect(cs)
cur = con.cursor()
cur.execute('select sum(column1) from table_name where column2 = any(%s)', [list(tup_ids)])
print(cur.fetchone())

Note that we always passed the parameters separately. 请注意,我们总是分别传递参数。 Do not be tempted to pass a query with Python-formatted values, as this is error prone and a safety issue ("SQL injection"), even if it looks simpler: 不要试图通过与Python格式化值的查询,因为这是容易出错和安全问题(“SQL注入”),即使它看起来更简单:

con = pg.connect(cs)  # do NOT do this:
q = con.query('select sum(column1) from table_name where column2 in %s' % (tup_ids,))

Please use "?" 请用 ”?” symbol in your SQL select command SQL select命令中的符号

In your case, you should revise to: 对于您的情况,您应该修改为:

conn.query('select sum(column1) from table_name where column2 in ?',(tup_ids,)) conn.query('从table_name中选择sum(column1),其中column2在?',(tup_ids,))

Then it should execute with success 然后它应该成功执行

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

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