Tom Martin
Tom Martin

Reputation: 13

data not being entered to database lotto program

import itertools
import sqlite3
import numpy


conn = sqlite3.connect('lotto.db')

con = conn.cursor()

con.execute('''CREATE TABLE IF NOT EXISTS lotto
        (num1 int,num2 int,num3 int,num4 int,num5 int, num6 int) ''')

con.execute('INSERT INTO lotto (num1,num2,num3,num4,num5,num6) VALUES (1,2,3,4,5,7)')

print(con.execute('SELECT * FROM lotto'))

for combo in itertools.combinations(range(1,10), 6):
    elements = (",".join(str(c) for c in combo))

    results = elements.split(',')
    results = map(int, results)

    con.execute('INSERT INTO lotto (num1,num2,num3,num4,num5,num6) VALUES (?,?,?,?,?,?)', results)

    avg = numpy.mean(results)

    print(avg)
    print(results)

con.close()

i have this code but it runs and doesnt input the list to the database, doesnt throw an error just runs through without any input prints fine and creates the table but just doesnt input any data.

i am quite new to python so any help would be greatly appreciated.

Upvotes: 0

Views: 85

Answers (1)

unutbu
unutbu

Reputation: 880489

Call commit before you close the connection:

conn.commit()
conn.close()

Per the docs:

This method commits the current transaction. If you don’t call this method, anything you did since the last call to commit() is not visible from other database connections. If you wonder why you don’t see the data you’ve written to the database, please check you didn’t forget to call this method.


Alternatively, you could use the connection as a context manager:

Connection objects can be used as context managers that automatically commit or rollback transactions. In the event of an exception, the transaction is rolled back; otherwise, the transaction is committed

with sqlite3.connect('lotto.db') as conn:
    cursor = conn.cursor()
    ...

Tip: Do not name the cursor con:

con = conn.cursor()

Variable names should be made as distinct as possible. Having con represent the cursor and conn represent the connection is asking for off-by-n errors. cur or cursor are common alternatives.

Upvotes: 1

Related Questions