调用三个表来插入数据。 (sqlite3的/蟒)

时间:2015-03-14 21:42:01

标签: python mysql sqlite

我已经规范化了三个表(Product,ProductType和ProductGender),我希望在我的主程序中调用它们,以便用户可以成功输入值并将数据存储在正确的表中。

以下是正在创建的SQL表

def create_product_table(): 
    sql = """create table Product
             (ProductID integer,
              Name text,
              primary key(ProductID))""" 
    create_table(db_name, "Product", sql)

def create_product_type_table():
    sql = """create table ProductType
             (ProductID integer,
             Colour text,
             Size text,
             Gender text,
             AmountInStock integer,
             Source text,
             primary key(ProductID, Colour, Size, Gender)
             foreign key(Gender) references ProductGender(Gender)
             foreign key(ProductID) references Product(ProductID))"""
    create_table(db_name, "ProductType", sql) 

def create_product_gender_table():
    sql = """create table ProductGender
             (Gender text,
             Price text,
             primary key(Gender))"""
    create_table(db_name, "ProductGender", sql)

以下是SQL子程序

def insert_data(values): 
    with sqlite3.connect("jam_stock.db") as db:
        cursor = db.cursor()
        sql = "insert into Product (Name, ProductID) values (?,?)"
        cursor.execute(sql,values)
        db.commit()

def insert_product_type_data(records): 
    sql = "insert into ProductType(Amount, Size, Colour, Source) values (?,?,?,?)"
    for record in records:
    query(sql,record)

def insert_product_gender_data(records): 
    sql = "insert into ProductGender(Gender, Price) values (?,?)"
    for record in records:
    query(sql, records)

def query(sql,data): #important 
    with sqlite3.connect("jam_stock.db") as db:
        cursor = db.cursor()
        cursor.execute("PRAGMA foreign_keys = ON") #referential integrity 
        cursor.execute(sql,data)
        db.commit() 

以下是用户输入值的代码。

if ans=="1": #1=to option 'Add Stock'
  a = input("Enter Gender: ")
  b = float(input("Enter Price: "))
  c = int(input("Enter ProductID: "))
  d = input("Enter Name: ")
  e = input("Enter Size: ")
  f = input("Enter Colour: ")
  g = input("Enter Source: ")
  h = input("Enter Amount: ")
  #code calling tables should be here

非常感谢帮助。严重不确定如何将3个表与用户的输入相关联。

这是我在规范化数据库之前所做的。因此,“产品”中的一个表将被更新,而不是添加现有产品。显然现在已经改变了,因为我已经创建了两个新表但是我无法成功添加产品,更不用说编辑一个了。

def update_product(data): #subroutine for editing stock
    with sqlite3.connect("jam_stock.db") as db:
        cursor = db.cursor()
        sql = "update Product set Name=?, Price=?, Amount=?, Size=?, Colour=?, Source=?, Gender=? where ProductID=?"
        cursor.execute(sql,data)
        db.commit()

0 个答案:

没有答案