July 24, 2024

Python micromount database -- database access

There may be more than one library for database access from python.
I am using "sqlite3".

The way I have the database set up, each record has 13 "fields", and I am surprised to find that when I do a SELECT to read them, I get a tuple with 13 things in it. This works fine, and has acted like a list up until I tried to change a field. We can use list(m) to make it into a list and then can change it -- but what will happen when we try to write it?

I was baffled as to why an UPDATE was not getting done. There was no error apparent, but the database was untouched. It turns out that a statement like this is required:

 self.conn.commit ()
Apparently any change to the database must be followed by a "commit" call. This requirement can by bypassed by setting a "autocommit" variable.

The data for an insert can be either a long tuple or a list, i.e. either of the following will work:

        data = ( "test", "spam" )
        data = [ "test", "spam" ]

        sql = '''INSERT INTO projects(name,info) VALUES(?,?)'''
        cur = conn.cursor ()
        cur.execute ( sql, data )
        conn.commit ()

Feedback? Questions? Drop me a line!

Tom's Mineralogy Info / tom@mmto.org