Connect SQLite to Python


This entry is part 5 of 2 in the series Python SQLite

We are going to use the sqlite3 library to be able to connect to SQLite database using Python. I will create a new SQLite database called emp.db. You can use whatever name you wish and store it into a directory of your choice.

Create SQLite Database and Table

In the following code, if the database does not yet exist, it will be created. The first three lines will create a new database file if it does not exist. What if it does already exist and you run those three lines again? That’s okay. No error happens in Python.

import sqlite3 
connection = sqlite3.connect("D:\Test\emp.db")
cursor = connection.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS Employees
    (Emp_Id INT, Name TEXT, Position TEXT)''')
connection.commit()
connection.close()

Now I will refactor this code a little bit. Wow can make variables for the names of the tables and the columns and the SQL string.

connection = sqlite3.connect("D:\Test\emp2.db")
cursor = connection.cursor()
sql_tablename = '''Employees'''
sql_columns = '''(Emp_Id INT, Name TEXT, Position TEXT);'''
sql_string = '''CREATE TABLE IF NOT EXISTS ''' + sql_tablename + sql_columns
print(sql_string) 

cursor.execute(sql_string)
connection.commit()
connection.close()

You may see code that doesn’t use a cursor, but it’s highly recommended to use one.

Series NavigationSQLite Cursor in Python >>

Leave a Reply