SQLite Tutorial

  • Home
  • Start Here
  • Views
  • Indexes
  • Triggers
  • Functions
    • Aggregate Functions
    • Date Functions
    • String Functions
    • Window Functions
  • API
    • SQLite Python
    • SQLite Node.js
    • SQLite Java
    • SQLite PHP
  • Try It
Home / SQLite Python / SQLite Python: Inserting Data

SQLite Python: Inserting Data

Summary: in this tutorial, you will learn how to insert rows into a table in the SQLite database from a Python program using the sqlite3 module.

To insert rows into a table in SQLite database, you use the following steps:

  1. First, connect to the SQLite database by creating a Connection object.
  2. Second, create a Cursor object by calling the cursor method of the Connection object.
  3. Third, execute an INSERT statement. If you want to pass arguments to the INSERT statement, you use the question mark (?) as the placeholder for each argument.

SQLite Python – inserting rows example

Let’s insert a new project into the projects table and some tasks into the tasks table that we created in the creating tables from a Python program tutorial.

Python SQLite Sample Database

First, create a new function to establish a database connection to an SQLitte database specified by the database file.

def create_connection(db_file): """ create a database connection to the SQLite database specified by db_file :param db_file: database file :return: Connection object or None """ conn = None try: conn = sqlite3.connect(db_file) except Error as e: print(e) return conn

Next, develop a function to insert a new project into the projects table.

def create_project(conn, project): """ Create a new project into the projects table :param conn: :param project: :return: project id """ sql = ''' INSERT INTO projects(name,begin_date,end_date) VALUES(?,?,?) ''' cur = conn.cursor() cur.execute(sql, project) conn.commit() return cur.lastrowid

In this function, we used the  lastrowid attribute of the Cursor object to get back the generated id.

Then, develop another function for inserting rows into the tasks table.

def create_task(conn, task): """ Create a new task :param conn: :param task: :return: """ sql = ''' INSERT INTO tasks(name,priority,status_id,project_id,begin_date,end_date) VALUES(?,?,?,?,?,?) ''' cur = conn.cursor() cur.execute(sql, task) conn.commit() return cur.lastrowid

After that, develop the main() function that creates a new project and two tasks associated with the project.

def main(): database = r"C:\sqlite\db\pythonsqlite.db" # create a database connection conn = create_connection(database) with conn: # create a new project project = ('Cool App with SQLite & Python', '2015-01-01', '2015-01-30'); project_id = create_project(conn, project) # tasks task_1 = ('Analyze the requirements of the app', 1, 1, project_id, '2015-01-01', '2015-01-02') task_2 = ('Confirm with user about the top requirements', 1, 1, project_id, '2015-01-03', '2015-01-05') # create tasks create_task(conn, task_1) create_task(conn, task_2)

And call the main() function:

if __name__ == '__main__': main()

Here is the full program:

import sqlite3 from sqlite3 import Error def create_connection(db_file): """ create a database connection to the SQLite database specified by db_file :param db_file: database file :return: Connection object or None """ conn = None try: conn = sqlite3.connect(db_file) except Error as e: print(e) return conn def create_project(conn, project): """ Create a new project into the projects table :param conn: :param project: :return: project id """ sql = ''' INSERT INTO projects(name,begin_date,end_date) VALUES(?,?,?) ''' cur = conn.cursor() cur.execute(sql, project) conn.commit() return cur.lastrowid def create_task(conn, task): """ Create a new task :param conn: :param task: :return: """ sql = ''' INSERT INTO tasks(name,priority,status_id,project_id,begin_date,end_date) VALUES(?,?,?,?,?,?) ''' cur = conn.cursor() cur.execute(sql, task) conn.commit() return cur.lastrowid def main(): database = r"C:\sqlite\db\pythonsqlite.db" # create a database connection conn = create_connection(database) with conn: # create a new project project = ('Cool App with SQLite & Python', '2015-01-01', '2015-01-30'); project_id = create_project(conn, project) # tasks task_1 = ('Analyze the requirements of the app', 1, 1, project_id, '2015-01-01', '2015-01-02') task_2 = ('Confirm with user about the top requirements', 1, 1, project_id, '2015-01-03', '2015-01-05') # create tasks create_task(conn, task_1) create_task(conn, task_2) if __name__ == '__main__': main()

Finally, connect to the database via sqlite3 shell and query data from the projects and tasks tables to check if the data has been inserted successfully.

Use these commands to format the output:

sqlite> .header on sqlite> .mode column

And use this SELECT statement to query data from the projects table:

SELECT * FROM projects;

And use the following SELECT statement to query data from the tasks table:

SELECT * FROM tasks;

In this tutorial, you have learned how to insert rows into tables in the SQLite database from a Python program.

  • Was this tutorial helpful ?
  • YesNo
Previous SQLite Python: Creating Tables
Next SQLite Python: Updating Data

Getting Started

  • What Is SQLite
  • Download & Install SQLite
  • SQLite Sample Database
  • SQLite Commands

SQLite Tutorial

  • SQLite Select
  • SQLite Order By
  • SQLite Select Distinct
  • SQLite Where
  • SQLite Limit
  • SQLite BETWEEN
  • SQLite IN
  • SQLite Like
  • SQLite IS NULL
  • SQLite GLOB
  • SQLite Join
  • SQLite Inner Join
  • SQLite Left Join
  • SQLite Cross Join
  • SQLite Self-Join
  • SQLite Full Outer Join
  • SQLite Group By
  • SQLite Having
  • SQLite Union
  • SQLite Except
  • SQLite Intersect
  • SQLite Subquery
  • SQLite EXISTS
  • SQLite Case
  • SQLite Insert
  • SQLite Update
  • SQLite Delete
  • SQLite Replace
  • SQLite Transaction

SQLite Data Definition

  • SQLite Data Types
  • SQLite Date & Time
  • SQLite Create Table
  • SQLite Primary Key
  • SQLite Foreign Key
  • SQLite NOT NULL Constraint
  • SQLite UNIQUE Constraint
  • SQLite CHECK constraints
  • SQLite AUTOINCREMENT
  • SQLite Alter Table
  • SQLite Rename Column
  • SQLite Drop Table
  • SQLite Create View
  • SQLite Drop View
  • SQLite Index
  • SQLite Expression-based Index
  • SQLite Trigger
  • SQLite VACUUM
  • SQLite Transaction
  • SQLite Full-text Search

SQLite Tools

  • SQLite Commands
  • SQLite Show Tables
  • SQLite Describe Table
  • SQLite Dump
  • SQLite Import CSV
  • SQLite Export CSV

SQLite Functions

  • SQLite AVG
  • SQLite COUNT
  • SQLite MAX
  • SQLite MIN
  • SQLite SUM

SQLite Interfaces

  • SQLite PHP
  • SQLite Node.js
  • SQLite Java
  • SQLite Python

About SQLite Tutorial

SQLite Tutorial website helps you master SQLite quickly and easily. It explains the complex concepts in simple and easy-to-understand ways so that you can both understand SQLite fast and know how to apply it in your software development work more effectively.

Looking for a tutorial…

If you did not find the tutorial that you are looking for, you can use the following search box. In case the tutorial is not available, you can request for it using the request for a SQLite tutorial form.

Recent Tutorials

  • SQLite IIF
  • SQLite Generated Columns
  • SQLite Getting Started
  • SQLite Programming Interfaces
  • SQLite Concat
  • SQLite INSTEAD OF Triggers
  • SQLite Join
  • SQLite IS NULL

Site Links

  • Home
  • About
  • Contact
  • Resources
  • Privacy Policy

Copyright Β© 2020 SQLite Tutorial. All Rights Reserved.