1
如何在SQL Alchemy v0.6.4中獲取日期時間列的MIN()
和文字日期時間?我想將日期時間結果限定在特定範圍內。我一直在使用sqlalchemy.func.min(column, literal_datetime)
。這似乎在SQLite中工作正常,但對MySQL無關緊要,這無疑意味着我正在討論這個錯誤。從MySQL錯誤是:如何選擇ORM屬性的MIN()和文字日期時間?
sqlalchemy.exc.ProgrammingError: (ProgrammingError) (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' '2011-06-14 12:30:00') AS min_1 \nFROM example' at line 1") 'SELECT min(example.my_datetime, %s) AS min_1 \nFROM example' (datetime.datetime(2011, 6, 14, 12, 30),)
- 我怎麼能夾住的datetime導致移植的方式?
- (難道我真的必須這樣做,在我的應用程序?)
這是我一直在使用,探討什麼問題 - 這裏所提出(使用基於內存的SQLite DB),沒有按正常工作「T使用MySQL:
#!/usr/bin/env python
import random
from datetime import datetime
import sqlalchemy as sa
import sqlalchemy.orm as orm
from sqlalchemy.ext.declarative import declarative_base
orm_base = declarative_base()
class MyClass(orm_base):
__tablename__ = "example"
pri_key = sa.Column(sa.Integer(), primary_key=True)
my_datetime = sa.Column(sa.DateTime(), index=True)
engine = sa.create_engine("sqlite:///:memory:", echo=True)
Session = orm.sessionmaker(bind=engine)
orm_base.metadata.bind = engine
orm_base.metadata.create_all()
# Create test-data
session = Session()
random.seed(1234567980)
for i in range(100):
month = random.randint(1, 12)
day = random.randint(1, 28)
hour = random.randint(0, 23)
minute = random.randint(0, 59)
my_instance = MyClass()
my_instance.my_datetime = datetime(2011, month, day, hour, minute)
session.add(my_instance)
session.commit()
session.close()
# Problem starts here
session = Session()
literal_datetime = datetime(2011, 06, 14, 12, 30)
print session.query(sa.func.min(MyClass.my_datetime)).one() # OK
print session.query(sa.func.min(MyClass.my_datetime, literal_datetime)).all() # Error in MySQL
我不是一個SQL專家,但數據庫可移植性是對我很重要,那麼如何避免陷阱這樣在未來的任何建議都歡迎。
謝謝,這確實對MySQL和SQLite都有效。 – RobM