As I said earlier, it is best to define a class in order to access a database. Here I again define a class called Table which allows me to insert data (additem). Unlike the example code for reading from the database, we here do not need to know the length of the database to read through all of its records.
The following code presupposes a table with two columns in it: the first field is the record identifier and the second is the record content.
class Table: def __init__(self, db, name): self.db = db self.name = name self.dbc = self.db.cursor() def additem(self, item): sql = "INSERT INTO " + self.name + " VALUES(" + id + ", " + item + ")" self.dbc.execute(sql) return
Rather than define the statement within the argument of self.dbc.execute, I here define it and then call it as an argument. If you have trouble with your script and it is giving unexpected output, try to define the variables separately from the arguments and then print them out. This will give you insight into the flow of the program and enable you to see where things are going awry.