【问题标题】:sqlalchemy.exc.InterfaceError: (sqlite3.InterfaceError) Error binding parameter 0 - probably unsupported typesqlalchemy.exc.InterfaceError: (sqlite3.InterfaceError) 错误绑定参数 0 - 可能是不支持的类型
【发布时间】:2020-04-05 15:32:05
【问题描述】:

所以我正在尝试使用 SQLAlchemy 将一些数据放入 SQLite DB。

我试图放入表中的 JSON 数据:

[{'type': 'paragraph', 'children': [{'text': 'A line of text in a paragraph.'}]}]

我的模特:

import datetime
from . import db, ma

class Books(db.Model):

    __tablename__ = 'books'

    id = db.Column(db.Integer, primary_key=True)
    content = db.Column(db.Text, nullable=False) 

    def __init__(self, content):
        self.content = content

class ContentSchema(ma.Schema):
        fields = ('content')

我的看法:

@main_blueprint.route('/add_book', methods=['POST'])
def add_book():

    books_data = request.get_json()

    new_book = Books(content=books_data)

    db.session.add(new_book)
    db.session.commit()

    return 'Success', 201

我收到的错误如下:

sqlalchemy.exc.InterfaceError: (sqlite3.InterfaceError) Error binding parameter 0 - probably unsupported type.
[SQL: INSERT INTO books (content) VALUES (?)]
[parameters: ([{'type': 'paragraph', 'children': [{'text': 'A line of text in a paragraph.'}]}],)]
(Background on this error at: http://sqlalche.me/e/rvf5)

如何将 JSON 数据放入数据库?

谢谢, 亚历克斯

【问题讨论】:

    标签: json flask flask-sqlalchemy


    【解决方案1】:

    content 字段需要文本

    books_data = request.get_json()
    new_book = Books(content=books_data)
    

    这里,它被输入了一个 JSON 对象。

    import json
    ...
    next_book = Books(content=json.dumps(books_data))
    

    应该解决这个问题。您需要在检索 content 后使用 json.loads() 来重构 JSON 对象,假设这是您需要的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多