After reading the database to python from the previous post here, it is time to do the ADD data to the database. Our database is created like this:
1 2 3 4 5 |
CREATE TABLE "drummers" ( "Id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "Name" TEXT, "Band" TEXT ) |
The database has autoincremented primary key, thus we do not need to add to it. With the help of InsertMany (a.k.a. bulk insert), one may loop through the tuples in an array and put everything to the database at once.
1 2 3 4 5 6 7 8 9 10 11 12 |
import sqlite3 def main(): conn = sqlite3.connect(r"C:\my.db") cur = conn.cursor() bands = [('Joe','Bananas'), ('Boris','The Glamours'), ('Christian', 'The Cox')] sql_command = """INSERT INTO drummers (Name,Band) VALUES (?,?)""" cur.executemany (sql_command, bands) conn.commit() if __name__== "__main__": main() |
The final version of the database looks like this: