[Tutor] A toy example to have clarity on Sqlite3 module
Manprit Singh
manpritsinghece at gmail.com
Tue Nov 16 11:33:36 EST 2021
Dear Sir ,
I have written an example of sqlite 3 module, without using a cursor
object . and with exception handling as given below:
import sqlite3
lang_list = [
("Fortran", 1957),
("Python", 1991),
("Go", 2009),
]
try:
con = sqlite3.connect("example.db")
# Create the table
con.execute("create table lang(name, first_appeared)")
# Fill the table
con.executemany("insert into lang values (?, ?)", lang_list)
except sqlite3.OperationalError: # It can handle if table already exists
print("Error! You may be trying to make a new table with same name")
else:
for row in con.execute("select * from lang"):
print(row)
finally:
con.close()
This example makes a database example.db, and a table lang.
In try block i have placed the creation of connection object along with the
execute method being called on this connection object to create the table,
then executemany method called on this connection object to insert the
sequence of rows data.
Since an error can occur in all three existing parts of the try block, i
have simply put all three in to try block only.
Secondarily here there is a sequence of rows to be inserted, that can only
be done with executemany, this can't be done with execute.
Secondarily - execute , executemany can be called on connection objects
also.
Secondarily I have put OperationalError: with except block that can handle
exception when it is produced due to making a table with same name which is
already existing.
In else block i am printing all the rows of the data.
Secondarily Inside finally block, con.close() to close the connection at
last
Just need to know, is this the correct implementation ? any suggestions
Regards
Manprit Singh
More information about the Tutor
mailing list