Site Sponsors:
SQL for Python3 - Keyed, Incremented, and Yielded 
One of the reasons why I blog so much is so I will always have my own code readily available.

Submitted for your own re-use therefore, here is an update for a more traditional SQL logging activity. Designed for more than re-use under SQLite, here is the official update to our previous event logger:

#!/usr/bin/env python3
import sqlite3

""" key + Log arbitrary "two string" information to an sqlite3 database """


class LogDB:
def __init__(self):
self.bOpen = False

def open(self):
""" Connect to the LOCAL database """
if self.bOpen == True:
return
self.conn = sqlite3.connect('PyLog2.sqlt3')
self.curs = self.conn.cursor()
self.bOpen = True

def createTable(self):
""" Create a table for the logged messages """
self.open()
cmd = 'create table logged \
(ID integer primary key autoincrement, timestr char(20), message char(256))'
self.curs.execute(cmd)
self.close()

def dropTable(self):
""" Remove the table from the database """
self.open()
cmd = 'drop table logged'
self.curs.execute(cmd)
self.close()

def insertRow(self, timestr, message):
""" Insert an arbitrary logge prefix & message """
self.curs.execute('insert into logged values(?,?,?)', [None, timestr, message])

def selectMessages(self):
""" Generator to enumerate thru selected values """
self.curs.execute('select * from logged')
for id, tstr, msg in self.curs.fetchall():
yield id, tstr, msg

def close(self):
""" Safe coding is no accident ... """
if self.bOpen:
self.conn.commit()
self.bOpen = False


if __name__ == "__main__":
db = LogDB()
db.createTable()
try:
db.open()
for ss in range(10):
db.insertRow("MyTime" + str(ss), "Message " + str(ss + 1))
for id, zt, mgs in db.selectMessages():
print(id, zt, mgs)
finally:
db.close()
db.dropTable()

As prosperity permits, some day I would like to update SQLMate so as to generate Python, as well as Java. ... I might even pay some attention to PEP08 (*)

Until that blessed day however (i.e. One can't type with one's fingers crossed (lol)), may this source be withe ye ... always = )

-Rn



(*) (Naaaa ... just re-factor & take credit for my work - care not, do I ;)

[ add comment ] ( 250 views )   |  permalink  |  related link

<<First <Back | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | Next> Last>>