Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

sqlite

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()
like image 596
Arturo Cuya Avatar asked Nov 15 '25 18:11

Arturo Cuya


1 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()
like image 82
match Avatar answered Nov 17 '25 10:11

match



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!