【问题标题】:SQLAlchemy: Error binding parameter 0 - probably unsupported typeSQLAlchemy:错误绑定参数 0 - 可能不受支持的类型
【发布时间】:2017-01-20 17:47:23
【问题描述】:

我正在尝试使用以下代码创建一个表的实例:

c = 'dcoh92j'
new_comment = Comment(rcomment = c, rtime = datetime.datetime.now())

但我收到此错误:

sqlalchemy.exc.InterfaceError: (sqlite3.InterfaceError) Error binding parameter 0 - probably unsupported type. [SQL: 'INSERT INTO comments (rcomment, rtime) VALUES (?, ?)'] [parameters: (Comment(id='dcoh92j'), datetime.datetime(2017, 1, 20, 12, 38, 38, 836433))

这是我的表架构:

class Comment(Base):
    __tablename__ = 'comments'
    id = Column(Integer, Sequence('comment_id_seq'), primary_key=True)
    rcomment = Column(String)
    rtime = Column(String)

    def __repr__(self):
        return "<Comment(rcomment='{0}', rtime='(1)')>".format(self.rcomment, self.rtime)
  1. 为什么 SQLAlchemy 认为我试图插入数据库的参数是(Comment(id='dcoh92j'), datetime.datetime(2017, 1, 20, 12, 38, 38, 836433)?而不仅仅是'dcoh92j'2017, 1, 20, 12, 38, 38, 836433
  2. Comment(id='dcoh92j') 来自哪里?

完整代码here.

【问题讨论】:

    标签: python sqlite sqlalchemy


    【解决方案1】:

    好吧,我终于弄明白了。当然,经过 3 小时的 bug 测试并扯掉我的头发,只需将 cdatetime.datetime.now() 包装在 str() 标记中即可。

    修复:

    new_comment = Comment(rcomment = str(c), rtime = str(datetime.datetime.now()))

    【讨论】:

      【解决方案2】:

      您将rtime = Column(String) 定义为字符串字段,但datetime.datetime.utcnow() 是日期时间对象。所以不要使用字符串字段,而是使用DateTime:

      from sqlalchemy import DateTime
      rtime = Column(DateTime)
      

      或将日期时间对象转换为字符串:

      str_rtime = str(datetime.datetime.utcnow())
      new_comment = Comment(rcomment=c, rtime=str_rtime)
      

      【讨论】:

      • 没用,你确定 DateTime 是一个对象吗?它参考rtime = Column(DateTime) 引发错误NameError: name 'DateTime' is not defined
      • 是的。你导入了吗from sqlalchemy import DateTime
      • 或者使用第二种方法不要改变你的字段类型只是将你的日期时间值转换为字符串
      • 谢谢,已经完成了一半。另一半将c 包装在str() 标记中。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-25
      相关资源
      最近更新 更多