Creating a sqlite database
When you want to start with using databases SQlite is a great tool. It provides an easy onramp to learn and prototype you database with a SQL compatible database.
First, let's import the libraries we need
import sqlite3
from sqlite3 import Error
SQlite doesn't need a database server, however, you have to start by creating an empty database file
import os
def check_for_db_file ():
if os.path.exists("mydatabase.db"):
print ("the database is ready")
else:
print("no database found")
check_for_db_file ()
no database found
Let's then create a function that will connect to a database, print the verison of sqlite and then close the connexion to the database.
def create_database(db_file):
""" create a database connection to a SQLite database """
try :
with sqlite3.connect(db_file) as conn:
print("database created with sqlite3 version {0}".format(sqlite3.version))
except Error as e:
print(e)
create_database(".\mydatabase.db")
database created with sqlite3 version 2.6.0
check_for_db_file ()
the database is ready
You're all set. From now on, you can open the database and write sql querries into it.