【问题标题】:SQLITE3 Integrity Error: Why am I getting this?SQLITE3 完整性错误:为什么我会得到这个?
【发布时间】:2018-10-06 22:12:05
【问题描述】:

我讨厌它无法准确说明错误是什么,但我已经探索过是否是导致此错误的数据类型。

这是我出错的函数:

def insert_recipe(recipe_id, recipe_name, img_link, recipe_link):
    with sql.connect('app.db') as connection:
        cursor = connection.cursor()
        cursor.execute("INSERT INTO recipes (recipe_id, recipe_name, img_link, recipe_link) VALUES (?,?,?,?)", (recipe_id, recipe_name, img_link, recipe_link))
        connection.commit()

这是错误页面:

这是我的功能,导致它显示在我的个人资料中:

@app.route('/profile', methods=['GET', 'POST'])
@login_required
def display_profile():
    id = request.values.get('id')
    title = request.values.get('title')
    img_link = request.values.get('img_link')
    link = request.values.get('link')
    print(type(id), type(title), type(img_link), type(link))
    insert_recipe(id, title, img_link, link)
    insert_savedRecipes(current_user.id, id)
    recipes = loadSavedRecipes()
    return render_template('profile.html', name=current_user.username, recipes=recipes)

我的 SQL 架构:

CREATE TABLE recipes (
  r_id integer PRIMARY KEY,
  recipe_id text NOT NULL,
  recipe_name text NOT NULL,
  img_link text NOT NULL,
  recipe_link text NOT NULL
);

我检查了所有列的数据类型,根据终端,它们都是字符串。此外,该函数似乎确实有效,因为它将配方插入到数据库表配方中。但是,当我单击导航栏中的配置文件选项卡时,这就是所有错误的时候。

所以当我的表格似乎正确插入时,我不确定为什么会出现此错误,如下图所示:

【问题讨论】:

    标签: sql flask sqlite


    【解决方案1】:

    表中的所有列都设置为NOT NULL,而第一个(R_ID)设置为PRIMARY KEY,无论如何不能为NULL。所以 - INSERT 必须插入所有 5 列才能正常工作。

    另一方面,您要插入 4 列。

    请注意您附加的屏幕截图的最后一行:

    sqllite3.IntegrityError: NOT NULL 约束失败:recipe.recipe_id

    因此,请确保您确实将 RECIPE_ID 传递给函数。

    【讨论】:

    • 是的,它确实传入了 recipe_id。那么当你插入到SQL数据库表中时,我以为r_id自然会被加到increment中呢?这不是它的实际工作方式吗?
    • 自然吗?不是,据我所知,除非您创建一个使用“身份”或“自动增量”或您使用的数据库系统中可能调用的任何内容的表。声明列 integer primary key 会在 SQLite 中自动执行,所以 - 是的,R_ID 将自动递增。但是,错误明确提到了 RECIPE_ID,所以 - 要么引擎在撒谎,要么你实际上没有传递它的值(尽管你声称你这样做了)。
    • 是的,它似乎实际上是通过我的打印语句传递值并且 r_id 自动递增,所以仍然不确定为什么 null 约束没有失败
    • 仅出于测试目的——如果你负担得起的话——删除表,然后重新创建它,而不为所有列指定 NOT NULL。再次运行您的代码,您将看到插入了什么,没有插入什么。我认为 RECIPE_ID 确实会保持为空(即 NULL)。
    猜你喜欢
    • 2016-11-25
    • 2019-01-25
    • 1970-01-01
    • 2013-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-18
    • 2019-03-25
    相关资源
    最近更新 更多