简体   繁体   English

Python-如何摆脱SQL查询执行中的转义序列

[英]Python - how to get rid of escape sequences in sql query execution

I am creating a sql query in python of the sort: 我正在使用以下方式在python中创建sql查询:

select lastupdatedatetime from auth_principal_entity where lastupdateddatetime < '02-05-16 03:46:51:527000000 PM'

When it is executed, there are escape sequences that are being added which doesn't return me answers. 执行该命令时,会添加一些转义序列,这些转义序列不会返回我的答案。

Although when we print it in stdout, it looks perfect, but for python's understanding it has escape sequences which I don't want in the execution command 虽然当我们在stdout中打印它时,它看起来很完美,但是为了python的理解,它具有我不希望在执行命令中使用的转义序列。

'select lastupdatedatetime from auth_principal_entity where lastupdateddatetime < \\'02-05-16 03:50:14:388000000 PM\\''

The escape sequences won't cause any problem in the cursor.execute(query) The real issue lies in the date that is being sent as a string is being used to compare and return values from db which are in date-object format. 转义序列不会在cursor.execute(query)中引起任何问题。真正的问题在于发送日期,因为使用字符串比较和返回db的日期对象格式的值。

so something like this should work. 所以这样的事情应该起作用。

query = "SELECT LASTUPDATEDDATETIME FROM AUTH_PRINCIPAL_ENTITY WHERE LASTUPDATEDDATETIME < to_date('03-May-16', 'dd-mon-yy')"

Or 要么

date_ = datetime.datetime.now().strftime('%d-%b-%y')
query = "SELECT LASTUPDATEDDATETIME FROM AUTH_PRINCIPAL_ENTITY WHERE LASTUPDATEDDATETIME < to_date('{}', 'dd-mon-yy')".format(date_)

Try that. 试试看 Should work for you :-) 应该为您工作:-)

For me, I wrap my SQL statements in triple quotes so it doesn't run into these issues when I execute: 对我来说,我将SQL语句用三引号引起来,这样我执行时就不会遇到这些问题:

query = """
    select lastupdatedatetime from auth_principal_entity where lastupdateddatetime < '02-05-16 03:46:51:527000000 PM'
    """

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

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