You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用cx_Oracle执行含单引号WHERE子句的SELECT语句出现语法错误

问题原因与解决方法

错误原因

你写的SQL语句用单引号包裹,但WHERE子句里的'USERNAME'又用了单引号,这会让Python误以为字符串在username=后面的单引号就结束了,后面的USERNAME变成了无意义的未定义标识符,直接触发语法错误。比如原代码里的这行:

c.execute('select username,created from dba_users where username='USERNAME' ')

Python会把'select username,created from dba_users where username='当成一个完整字符串,后面的USERNAME就成了游离的代码,自然报错。

解决办法

给你几种可行的修正方式:

  • 用双引号包裹整个SQL语句:这样内部的单引号就不会和外层冲突

    c.execute("select username,created from dba_users where username='USERNAME' ")
    
  • 转义内部单引号:在内部单引号前加反斜杠\,告诉Python这是字符串的一部分,不是结束标记

    c.execute('select username,created from dba_users where username=\'USERNAME\' ')
    
  • 用三引号包裹SQL语句:三引号允许字符串内部自由使用单引号或双引号,不用转义

    c.execute('''select username,created from dba_users where username='USERNAME' ''')
    
  • 参数绑定(推荐):这不仅能避免语法问题,还能防止SQL注入,是操作数据库的最佳实践

    c.execute('select username,created from dba_users where username=:1', ('USERNAME',))
    

内容的提问来源于stack exchange,提问作者varun kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 00:45:11