python sql 参数化_Python,SQL:将列设置为参数

I have a SQL query, mad in Python using Psycopg2. The query reads some columns from the arches table:

rows = archesDB.read_all("""SELECT "+str(columns)[1:-1].replace("'","")+"

FROM arches

WHERE lower(arch) like '%%%s%%'""" % (arch.lower()))

I want to parametrize this query, so that it will not specify the columns needed using string concatenation, but as parameters - a far more elegant way.

The naïve way is to SELECT *, and filter out the columns I need. But this burdens the DB and network with unneeded data, so I rather avoid it.

Any ideas?

Adam

解决方案

Column names cannot be passed in the SQL string as parameters within the DB API. And it would not make sense to it as well.

If you need to check the column name input, sanitize it beforehand.

The like string should go in as a parameter though

The following code sample would be an improvement if columns variable contains a list of strings for the column names:

rows = archesDB.read_all("""SELECT %s

FROM arches

WHERE lower(arch) like %%s""" % (",".join(columns),),

("%%%s%%" % (arch.lower(),),))

First, the column names are inserted within first substitution (%s) and the last %%s is converted to %s.

Then the ("%%%s%%" % (arch.lower(),),) makes a string with %string_content%.

And at last, db api escapes the %string_content% and adds quotes to it that finally makes the query.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值