【问题标题】:How to use the same code for both sqlite and postgres如何对 sqlite 和 postgres 使用相同的代码
【发布时间】:2023-01-12 03:02:26
【问题描述】:

我的 sqlalchemy 代码需要同时支持 sqlite 和 postgres,但现在它不适用于 sqlite。

sqlalchemy.exc.StatementError: (builtins.TypeError) SQLite DateTime 类型只接受 Python datetime 和 date 对象作为输入。

我检查了Error - "SQLite DateTime type only accepts Python " "datetime and date objects as input.",但在我的整个代码库中进行此更改是不可能的,因为它有不止一个地方使用日期字符串而不是日期时间

这是我的代码,它适用于 postgres 引擎,但不适用于 sqlite,我可以修改除上述链接建议之外的任何内容,以便我的代码在 sqlite 和 postgres 上运行

from sqlalchemy import create_engine, Column, Integer
from sqlalchemy.orm import declarative_base, Session
from sqlalchemy.types import DateTime

Base = declarative_base()

class Foo(Base):
    __tablename__ = "foo"
    id = Column(Integer, primary_key=True)
    col = Column(DateTime)

engine = create_engine("postgresql://tony:tony@localhost:5432")
# engine = create_engine("sqlite:///db.db")
Base.metadata.create_all(engine)

with Session(engine) as session:
    session.add(Foo(col='2023-01-07T11:08:31Z'))
    session.commit()

【问题讨论】:

    标签: python sql postgresql sqlite sqlalchemy


    【解决方案1】:

    DB-API 规范期望 SQL DATETIME 作为 python datetime.datetime (docs) 提供。

    我相信 psycopg2 提供了一个可以处理 ISO 8601 格式字符串的扩展,但这是一个扩展。

    如果您想要最兼容,请使用 datetime.datetime 对象来传递和检索日期。

    另外为什么要从 sqlalchemy.types 导入 DateTime ?它可以直接在sqlalchemy下获得。

    from datetime import datetime
    
    from sqlalchemy import Column, Integer, create_engine, DateTime
    from sqlalchemy.orm import Session, declarative_base
    
    Base = declarative_base()
    
    
    class Foo(Base):
        __tablename__ = "foo"
        id = Column(Integer, primary_key=True)
        col = Column(DateTime)
    
    
    engine = create_engine("postgresql+psycopg2://postgres:postgres@localhost:5432/postgres") # OK
    engine = create_engine("sqlite:///db.db") # OK
    
    Base.metadata.create_all(engine)
    
    with Session(engine) as session:
        session.add(Foo(col=datetime.fromisoformat("2023-01-07T11:08:31Z")))
        session.commit()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-22
      • 2019-11-26
      • 1970-01-01
      • 2017-01-03
      • 1970-01-01
      • 2015-05-15
      • 1970-01-01
      相关资源
      最近更新 更多