【问题标题】:problem with exec'ing python sqlite3 execute commandexec'ing python sqlite3执行命令的问题
【发布时间】:2021-02-12 05:02:26
【问题描述】:

虽然我实际上希望获得更复杂的查询,但我有以下(工作)查询(在 3.8 python 中):

aa =  conn2.execute("select proj from (select distinct proj from \
      top_table group by proj) where proj = \'xx\' group by proj;")

这将返回一个我可以在其上运行fetchall() 的对象。但是当我尝试使用exec 时,制作:

aa =  exec ("conn2.execute(\"select proj from (select distinct proj \
      from top_table group by proj) where proj = \'%s\' group by proj;\")" % t)

t ='xx', aa 返回Nonetype。另外,当我将print 换成conn2.execute 并最终得到:

aa =  exec ("print(\"select proj from (select distinct proj from \
      top_table group by proj) where proj = \'%s\' group by proj;\")" % t)

它返回:

select proj from (select distinct proj from top_table group by proj)\
where proj = 'xx' group by proj;

我可以将其粘贴到 sqlite3 shell 中并返回正确的值。

有没有人在使用exec 命令的子查询时遇到过这样的问题?

注意,对于大多数人来说,可能有太多的组/不同的语句,但这是从一个更长的命令中删除的,它按原样运行(只是不使用 exec)。

【问题讨论】:

  • 为什么需要exec()?为什么不使用普通的字符串格式来创建查询?或者,也许您应该将t 通常作为参数 - execute(QUERY, args=(t,)) 并将其放在正确的位置。
  • 顺便说一句:print() 在屏幕上发送文本并始终返回None,因此使用print() 是没用的。也许更好地学习如何正确使用execute() 或如何格式化字符串。
  • print() 只是说明了变量替换后的字符串,表明正在向 execute() 发送有效命令。你是对的,在这种情况下我似乎不需要 exec 。我只是倾向于在那种类型的字符串替换上使用它,因为a)它比单独格式化字符串少一个步骤,b)我有时使用字符串替换来构建命令并运行它们,所以我只是习惯使用它。

标签: python python-3.x sqlite


【解决方案1】:

坦率地说,使用exec 是最愚蠢的想法。


您甚至可以使用普通的字符串格式 - "text '{}' text".format(t)

query = """select proj from 
           (select distinct proj from top_table group by proj) 
           where proj = '{}' group by proj;""".format(t)

或 f-string - f"text '{t}' text"

query = f"""select proj from 
            (select distinct proj from top_table group by proj) 
            where proj = '{t}' group by proj;"""

最终老了% - "text '%s' text" % t

query = f"""select proj from 
            (select distinct proj from top_table group by proj) 
            where proj = '%s' group by proj;""" % t

以后再用

conn2.execute(query)

但最好检查它是否适用于 execute 中的参数 - 它应该用 t 代替 ?

query = """select proj from 
           (select distinct proj from top_table group by proj) 
           where proj = ? group by proj;"""

conn2.execute( query, (t,) )

即使你只有一个参数,它也必须是元组 - (t,)

你也可以试试带参数的字典,它应该用t代替:value

query = """select proj from 
           (select distinct proj from top_table group by proj) 
           where proj = :value group by proj;"""

conn2.execute( query, {'value': t} )

使用?:value 应该会自动添加' ',您不必使用它。

SQLite 文档:execute

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-21
    • 2023-02-14
    • 2015-05-12
    • 2015-01-10
    • 2020-12-23
    • 1970-01-01
    • 2011-12-01
    • 1970-01-01
    相关资源
    最近更新 更多