首页 > 解决方案 > Python - SQLite - 根据元组信息插入值

问题描述

我有一个 sqlite 表:

conn.execute("""CREATE TABLE IF NOT EXISTS students(
                        ID integer not null primary key,
                        Department text ,
                        Standing text ,
                        GPA real, 
                        unique(ID) 
                    );""")

我有一个元组列表:

all_info =[('MATH', 70, 10, 20), ('BIOLOGY', 82, 12, 15), ('CHEMISTRY', 78, 30, 20), ('COMPUTER SCIENCE', 113, 5, 15), ('INFORMATICS', 138, 16, 2), ('ENGLISH', 94, 17, 33), ('SPANISH', 118, 7, 42), ('BIOCHEMISTRY', 104, 14, 39),

元组包含每个部门的学生人数信息。比如数学系有70名优等生,10名见习生和20名普通学生,总共有100名学生。

我需要根据元组中的信息将数据插入到学生数据库中。学生表的期望结果:

ID    Department   Standing   GPA  
1     Math         Honors     93
2     Math         Honors     93
3     Math         Probation  60
...and so on.
(there would be 70 entries of math students in Honors standing with a GPA of 93.)

如果学生是荣誉学生,他们的 GPA 将是 93,如果学生处于试用期,他们的 GPA 将是 60,如果学生处于正常状态,他们的 GPA 将是 80。

我无法根据元组列表中的信息以编程方式将值插入到学生表中。

谢谢你。

编辑1:我被困在从哪里开始,我想循环遍历元组列表

for item in all_info:
    ID = randint(1,99999)
    num_honor = item[1]
    num_prob = item[2]
    num_norm = item[3]
   cur.execute(INSERT statement..)

但这只会输入每个元组中的内容,根据元组中的数字插入行的任何想法?

标签: python-3.xsqlite

解决方案


这就是你要找的

for each_tuple in all_info:
  Department = each_tuple[0]
  students_list = [(Department, 'Honors', 93) for i in range (0, each_tuple[1])] + [(Department, 'Probation', 60) for i in range (0, each_tuple[3])]+ [(Department, 'Normal', 80) for i in range (0, each_tuple[2])]

  cur.executemany('INSERT INTO students VALUES(?,?,?);',student_list)

推荐阅读