SQLAlchemy:错误绑定参数0 - 可能不支持的类型

时间:2017-01-20 17:47:23

标签: python sqlite sqlalchemy

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

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')来自何处?
  3. 完整代码here

2 个答案:

答案 0 :(得分:2)

好的,我最终搞清楚了。当然,在经过3个小时的bug测试并撕掉我的头发之后,将cdatetime.datetime.now()包装在str()标签中是一件简单的事情。

修正:

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

答案 1 :(得分:1)

您将rtime = Column(String)定义为字符串字段,但datetime.datetime.utcnow()是日期时间对象。因此,使用DateTime

代替字符串字段
from sqlalchemy import DateTime
rtime = Column(DateTime)

或将datetime对象转换为字符串:

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