【问题标题】:Creating a table inside a table in sqlite 3 (python)在sqlite 3(python)中的表内创建表
【发布时间】:2013-04-11 13:21:50
【问题描述】:

我正在尝试为食谱存储程序创建一个 sqlite 数据库,该数据库包含食谱表中的人数、成分、烹饪温度和烹饪时间。我打算在成分部分创建另一个表,以存储“id”(它将自动递增);质量数(例如,200);质量类型(例如 g)和食物类型(例如面粉)。

我正在使用此代码来尝试获取变量并存储它们:

    def setIngredientsInRecipe(recipeName):
        cursor.execute("""INSERT INTO %s(ingredients) CREATE TABLE\
                    (ID INT PRIMARY KEY AUTO_INCREMENT, MassNumber VARCHAR(10), MassType VARCHAR(50) FoodType VARCHAR(50))""" % (recipeName))
        print ""
        massNoInput = raw_input("Please enter your first ingredient mass(just the number): ")
        massTypeInput = raw_input("Now please input the mass type (grams etc): ")
        foodInput = raw_input("Please enter your first ingredient type: ")

        cursor.execute("""INSERT INTO %s(ingredients(MassNumber)) VALUES('%s')""" % (recipeName,massNoInput))
        cursor.execute("""INSERT INTO %s(ingredients(MassType)) VALUES('%s')""" % (recipeName,massTypeInput))
        cursor.execute("""INSERT INTO %s(ingredients(FoodType)) VALUES('%s')""" % (recipeName,foodInput))

        return recipeName

显然我稍后会添加一些数字检查,以先查看输入是否有效。

它在第一个 cursor.execute 行崩溃,说这是一个语法错误...

如果有人能向我解释如何解决这个问题,我将不胜感激,我已经研究这段代码很久了!

谢谢, 瑞恩 :)

【问题讨论】:

  • 您无法将表插入另一行。您的 SQL 语法无效。
  • 好的,所以我需要考虑另一种方法......无论如何谢谢:)
  • 创建一个表并将您的数据插入到该表中。

标签: python sqlite python-2.7


【解决方案1】:

使用两张表,一张用于食谱,一张用于配料,并为每种配料记录其所属食谱的 ID:

CREATE TABLE recipe(ID, People, CookingTime);
CREATE TABLE ingredient(ID, RecipeID, MassNumber, MassType, FoodType);

要将一种成分添加到配方中,只需在该表中插入一条记录 (这里,42 是配方的 ID):

INSERT INTO ingredient(RecipeID, MassNumber, MassType, FoodType) VALUES (42, ...)

【讨论】:

猜你喜欢
  • 2017-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-27
  • 1970-01-01
  • 1970-01-01
  • 2020-09-15
  • 2021-01-19
相关资源
最近更新 更多