user5077528
user5077528

Reputation:

Python sqlite3 saving data

Does anyone know how do I correct this as this code is not saving the data in a database?

def save():

    #FUNCTIONS

    def savenow():
        params = [i.get(), n.get(), p.get(), r.get(), t.get(), a.get(), "None", "None"]

        if not os.path.exists("C:/Users/Dhruv/DS"):
            os.makedirs("C:/Users/Dhruv/DS/")

        connect = sqlite3.connect("C:/Users/Dhruv/DS/data.db")
        connect.execute("""CREATE TABLE IF NOT EXISTS FD 
                        (ID TEXT NOT NULL,
                         NAME TEXT NOT NULL,
                         P INT NOT NULL,
                         R INT,
                         T INT,
                         A INT NOT NULL,
                         D1 DATE,
                         D2 DATE);""")

        tobeexec = "INSERT INTO FD(ID, NAME, P, R, T, A, D1, D2) VALUES(?, ?, ?, ?, ?, ?, ?, ?)"

        connect.execute(tobeexec, params);

        connect.close()

I just want to write the data in the database but when I am trying to retrieve it, it shows that the database is empty... Anyway thanks in advance...

Upvotes: 0

Views: 354

Answers (2)

mgc
mgc

Reputation: 5443

In addition to the best answer, think also to the use of the Connection object as a context manager, it can be useful and it is provided in the SQLite3 API :

connect = sqlite3.connect("C:/Users/Dhruv/DS/data.db")
try:
    with connect:
        connect.execute(...)  # Your SQL statement
except Exception as err:
    # Do what you want with the Exception

If your statement(s) within the with connect don't raise error, the transaction will be committed automatically. If something goes wrong the transaction is rolled back.

(Another answer could be to set the isolation_level to None after loading the db, which will implies an autocommit mode)

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599490

You need to commit the transaction.

connect.execute(tobeexec, params);
connect.commit()
connect.close()

Upvotes: 1

Related Questions