Create sqlite connection

From TRCCompSci - AQA Computer Science
Revision as of 19:27, 12 April 2019 by Admin (talk | contribs) (Created page with "=Code= <syntaxhighlight lang=python> import sqlite3 from sqlite3 import Error def create_connection(db_file): """ create a database connection to a SQLite database """...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Code

import sqlite3
from sqlite3 import Error
 
 
def create_connection(db_file):
    """ create a database connection to a SQLite database """
    try:
        conn = sqlite3.connect(db_file)
        return conn
    except Error as e:
        print(e)
        return none

connection = create_connection("test.db") # example of how to call the method

You will need to import 'sqlite3' this should be automatically installed as part of python, so it should allow you to import it without doing anything else. The example above also imports 'Error' from sqlite3 inorder to use exception handling.

The code 'sqlite3.connect' will connect to a database if it exists, or it will create the database if it doesn't currently exist.