SQLite Python: Creating Tables

Summary: in this tutorial, you will learn how to create tables in an SQLite database from the Python program using the sqlite3 module.

Creating new tables from Python

To create a new table in an SQLite database from a Python program, you follow these steps:

First, import the built-in sqlite3 module:

import sqlite3Code language: JavaScript (javascript)

Next, create a connection to an SQLite database file by calling the connect() function of the sqlite3 module:

with sqlite3.connect(database) as conn:Code language: JavaScript (javascript)

The connect() function returns a Connection object that represents the database connection to the SQLite file specified by the database argument.

Then, create a Cursor object by calling the cursor() method of the Connection object:

cursor = conn.cursor()

After that, pass the CREATE TABLE statement to the execute() method of the Cursor object to execute the statement that creates a new table:

cursor.execute(create_table)Code language: CSS (css)

Finally, apply the changes to the database by calling the commit() function:

conn.commit()Code language: CSS (css)

Here’s the complete code:

import sqlite3

database = '<your_database>'
create_table = '<create_table_statement>'

try:
    with sqlite3.connect(database) as conn:
        cursor = conn.cursor()
        cursor.execute(create_table)   
        conn.commit()

except sqlite3.OperationalError as e:
    print(e)Code language: Python (python)

For demonstration purposes, we will create two tables: projects and tasks as shown in the following database diagram: