使用SQL多行输入

时间:2016-03-02 14:39:40

标签: python sqlite python-2.7

我想通过编写游戏(基于文本)来学习Python和SQLite。我想将数据插入到SQLite DB中。我为玩家创建了一个表格

c.execute('''CREATE TABLE player(ID_Player INTEGER PRIMARY KEY, Age INT, Name VARCHAR, Position VARCHAR, Skill INT, Value INT)''')

现在我想为此表插入n个条目。对于每一列,我想应用一个确定应输入内容的函数。

  • 适合年龄:randint(18,33))
  • for Name:names.get_full_name(gender =' male')
  • for Position:random.choice(positions)
  • for Skill:randint(50,100)
  • for Value:randint(500000,5000000)

如果我手动创建列表,看起来像这样

multi_lines =[ (25,'Playern Name1','TW',95,45000000),
               (26,'Playern Name2','ST',75,3500000),
               (32,'Playern Name3','IV',85,25000000),]

比我可以执行它们并使用函数c.executemany('INSERT INTO player(age, name, position, skill, value) VALUES (?,?,?,?,?)', multi_lines)将它们插入到我的数据库中 我试图确定输入om c.executemany,但这不起作用。

c.executemany('INSERT INTO player(Age, Name, Position, Skill, Value)  VALUES (?,?,?,?,?)',\
               (randint(18,33),names.get_full_name(gender='male'),random.choice(positions),randint(50,100), randint(500000,50000000) ))

接下来,我尝试制作了许多列表并将它们放入一个空列表中:

lst = []
positions = ['TW', 'IV', 'MF', 'ST']

for i in range(2):
    lst.append(randint(18,33))
    lst.append(names.get_full_name(gender='male'))
    lst.append(random.choice(positions))
    lst.append(randint(50,100))
    lst.append(randint(500000,5000000))

print  lst

此输出为[19, u'Ricardo Moore', 'ST', 68, 3298618, 26, u'Carl Cole', 'ST', 92, 3380302],但是,我想在multi_lines中创建输出。这可能是一个合乎逻辑的方法吗?或者更具体地说,如何创建另一个列表中的列表?

main_list = [
    (list_1),
    (list_2),
    (list_n)
]

1 个答案:

答案 0 :(得分:1)

您需要executemany()列表

positions = ['TW', 'IV', 'MF', 'ST']
multi_lines = [[
        randint(18,33),
        names.get_full_name(gender='male'),
        random.choice(positions),
        randint(50,100),
        randint(500000,5000000)
    ]
    for i in range(2)
]

c.executemany('INSERT INTO player(Age, Name, Position, Skill, Value)  VALUES (?,?,?,?,?)', multi_lines)