4

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()
1
  • 1
    Probably unrelated, but AUTOINCREMENT in sqlite doesn't really do what most people think it does. It's not necessary unless you want to be absolutely sure that after a row is deleted, its ID will never be reused. Commented Jan 19, 2018 at 21:37

1 Answer 1

4

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()
Sign up to request clarification or add additional context in comments.

Comments

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.