2

I want to learn Python and SQLite by programming a game (text based). I would like to insert data into a SQLite DB. I created a tabel for players

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

Now I would like to insert n entries for this table. And for each column, I would like to apply a function that determines what should be entered.

  • for age: 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)

If I manually create the lists, which looks like this

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

than I can execute them and they are inserted to my DB with the function c.executemany('INSERT INTO player(age, name, position, skill, value) VALUES (?,?,?,?,?)', multi_lines) I tried to determine the inputs om c.executemany but this did not work.

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) ))

Next, I tried to make many lists and put them into an empty list:

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

the output of this was [19, u'Ricardo Moore', 'ST', 68, 3298618, 26, u'Carl Cole', 'ST', 92, 3380302], however, I would like to create outputs like in multi_lines. What could be a logical way to do this? Or more specifically, how can I create a list which is in another list ?

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

1 Answer 1

1

You need a list of lists for 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)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! It worked! I was almost there just could not figure out where to put the for statement.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.