简体   繁体   English

如何在sqlalchemy中执行原始SQL中的当前日期

[英]How to pass current date in raw sql in sqlalchemy execute

I want to update a datetime column in mysql database. 我想更新mysql数据库中的datetime列。 The application uses sqlalchemy but for some reason I have to pass a raw sql here. 该应用程序使用sqlalchemy,但由于某些原因,我必须在此处传递原始sql。 The query is 查询是

from sqlalchemy import func
session.execute(text("update table set col1=:value, date=:curr_date"),{'value:' my_value, 'curr_date:' func.now()})

The query throws an error expected string or buffer near 'curr_date:' func.now()}) . 查询在'curr_date:' func.now()})附近引发错误的expected string or buffer How do I format the return value to string? 如何将返回值格式化为字符串? Even if I do format it to string, how would it be converted to datetime when inserted into database? 即使我将其格式化为字符串,插入数据库后如何将其转换为日期时间?

I'd suggest reading up a bit on SQLAlchemy's TextClause.bindparams . 我建议您阅读一下SQLAlchemy的TextClause.bindparams I think that may be what you're looking for. 我认为这可能是您要寻找的。 For the current datetime, I'd recommend just using datetime.datetime.now() . 对于当前日期时间,我建议仅使用datetime.datetime.now() Please see below: 请看下面:

from sqlalchemy import text
import datetime

stmt = text("UPDATE test_table SET name=:value, update_date=:curr_date WHERE id=:the_id")
stmt = stmt.bindparams(the_id=1, value='John', curr_date=datetime.datetime.now())
session.execute(stmt)  # where session has already been defined

Using the following environment, I tried the above code with a session and it worked just fine: 使用以下环境,我在会话中尝试了上面的代码,并且工作正常:

OS X El Capitan
MySQL Server 5.7
PyMySQL (0.7.2)
SQLAlchemy (1.0.12)
Python 3.5.1

I hope that helped! 希望对您有所帮助!

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

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