简体   繁体   English

我如何识别字符串是否应该带参数

[英]How can I identify if a string should take an argument

I am not sure if there is a pretty way of doing this but here is my problem: 我不确定是否有这样做的漂亮方法,但这是我的问题:

I have a dict that reference to some SQL statements: 我有一个字典,引用了一些SQL语句:

{
  'var1': """select * from sometable where x=%s"""
  'var2': """select * from sometable"""
}

I have a script which will either use var1 or var2... but obviously when attempting to pass an argument to var2 it will throw an exception... 我有一个将使用var1或var2的脚本...但是显然,当尝试将参数传递给var2 ,它将引发异常...

I was wondering if there is a way to identify if a string needs an argument and only then try to pass it... 我想知道是否有一种方法可以识别字符串是否需要参数,然后才尝试传递它。

A simple way would be to count the %s strings. 一种简单的方法是计算%s字符串。

Could fail in some extreme cases, but basically 在某些极端情况下可能会失败,但基本上

sql_string.count('%s')

provides you with the number of expected arguments. 为您提供了预期的参数数量。

d = {
  'var1': """select * from sometable where x=%s""",
  'var2': """select * from sometable"""
}

for k,v in d.items():
    print("{}, {} args".format(k,v.count("%s")))

result: 结果:

var2, 0 args
var1, 1 args

had you other formats than %s you could use a regular expression to match other formats, like this: 除了%s以外,还有其他格式可以使用正则表达式匹配其他格式,例如:

len(re.findall("%[ds]",sql_string)

Both solutions above are far from perfect. 上面的两个解决方案都不是完美的。 They don't handle % escaping for instance. 例如,他们不处理%转义。

Do you mean? 你的意思是?

if "%s" in sql_stmt:
    do_something()

Also you can use sql_stmt.count('%s') to get the number of arguments. 您也可以使用sql_stmt.count('%s')来获取参数数量。

dict = {
  "var1": "select * from sometable where x=%s",
  "var2": "select * from sometable"
}
for k,v in dict.iteritems():
    if "%s" in v:
        print "[%s] needs an argument"%v
    else:
        print "[%s] doesn't need an argument"%v

gives : 给出:

[select * from sometable where x=%s] needs an argument
[select * from sometable] doesn't need an argument

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

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