Difference between revisions of "Create sqlite connection"
(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 """...") |
|||
Line 1: | Line 1: | ||
− | |||
<syntaxhighlight lang=python> | <syntaxhighlight lang=python> | ||
import sqlite3 | import sqlite3 |
Latest revision as of 19:27, 12 April 2019
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.