How to initialize a database just once on Python using SQLite 3?

Question:

I’m trying to make a python app where the user can add a row to a table and visualize all the rows. My problem is that it seems that every time I run the program, the database is created again, with no values. I say this because there is an autoincrement value that is always the same. When I write the program again on the cmd and insert the values by hand it does show me more than one value.

Here’s the code:

import sqlite3

conn = sqlite3.connect("amigo_local_db.db")
c = conn.cursor()

c.execute("CREATE TABLE IF NOT EXISTS images (id INTEGER PRIMARY KEY AUTOINCREMENT, url TEXT, bash TEXT)")

action = int(input("Insert an action: (1: Add row | 2: Close)"))
if(action == 1):
    url = input("URL: ")
    bash = input("BASH: ")
    values = (url,bash)
    c.execute("INSERT INTO images VALUES(null,?,?)",values)
else:
    conn.close()
    quit()

for row in c.execute("SELECT * FROM images"):
    print(row)

conn.close()
Asked By: Arturo Cuya

||

Answers:

You need to commit the INSERT transaction before closing, or it will not be persisted:

import sqlite3

conn = sqlite3.connect("amigo_local_db.db")
c = conn.cursor()

c.execute("CREATE TABLE IF NOT EXISTS images (id INTEGER PRIMARY KEY AUTOINCREMENT, url TEXT, bash TEXT)")

action = int(input("Insert an action: (1: Add row | 2: Close)"))
if(action == 1):
    url = input("URL: ")
    bash = input("BASH: ")
    values = (url,bash)
    c.execute("INSERT INTO images VALUES(null,?,?)",values)
    conn.commit()
else:
    conn.close()
    quit()

for row in c.execute("SELECT * FROM images"):
    print(row)

conn.close()
Answered By: match
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.