จะส่งวันที่ปัจจุบันใน raw sql ในการดำเนินการ sqlalchemy ได้อย่างไร

ฉันต้องการอัปเดตคอลัมน์ datetime ในฐานข้อมูล mysql แอปพลิเคชันใช้ sqlalchemy แต่ด้วยเหตุผลบางอย่างฉันต้องส่ง raw sql ที่นี่ คำถามคือ

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

แบบสอบถามแสดงข้อผิดพลาด expected string or buffer ใกล้ 'curr_date:' func.now()}) ฉันจะจัดรูปแบบค่าส่งคืนเป็นสตริงได้อย่างไร แม้ว่าฉันจะจัดรูปแบบเป็นสตริง แต่จะถูกแปลงเป็นวันที่และเวลาเมื่อแทรกลงในฐานข้อมูลได้อย่างไร


person user3527975    schedule 10.05.2016    source แหล่งที่มา


คำตอบ (1)


ฉันขอแนะนำให้อ่าน สักหน่อย TextClause.bindparams ของ SQLAlchemy ฉันคิดว่านั่นอาจเป็นสิ่งที่คุณกำลังมองหา สำหรับวันที่และเวลาปัจจุบัน ฉันขอแนะนำให้ใช้เพียง datetime.datetime.now() โปรดดูที่ด้านล่าง:

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

เมื่อใช้สภาพแวดล้อมต่อไปนี้ ฉันลองใช้โค้ดด้านบนกับเซสชันและทำงานได้ดี:

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

ฉันหวังว่ามันจะช่วยได้!

person John Adjei    schedule 10.05.2016
comment
ขอบคุณสำหรับข้อเสนอแนะ ฉันทราบแล้วdatetime.datetime.now() ฉันกำลังมองหาบางอย่างโดยใช้ func.now() - person user3527975; 17.05.2016