16-5. Connect to Database

Using an SQLite database follows a standard procedure as below:

  • Establish a connection with the database.
  • Retrieve a cursor for the database.
  • Execute operations on the database.
  • Apply changes to the database.
  • Terminate the connection to the database.

 

Establish a connection with the database

 

To perform an SQL operation on an SQLite database:

  • Formulate a string containing the SQL command
  • Invoke the execute method of the Cursor object, passing the SQL string as an argument

For example,

cur.execute("CREATE TABLE IF NOT EXISTS contacts (id INTEGER PRIMARY KEY, name TEXT, email TEXT, GPA REAL)")