Last Updated : 01 Jul, 2025
This article explains how to insert data into an SQLite table from Python using the sqlite3 module. The INSERT INTO statement is used to insert new rows into a table. There are two main methods for inserting data:
Let's discuss both these methods in detail with example:
1. Insert Data Using Only ValuesIn this approach, we insert data by specifying the values for all columns without mentioning column names.
Syntax:ExampleINSERT INTO table_name VALUES (value1, value2, value3,...);
Below is a program that depicts how to insert data in an SQLite table using only values. Then display the content of the table and commit it to the database.
Python
import sqlite3
# Connect to SQLite database
conn = sqlite3.connect('geeks2.db')
cursor = conn.cursor()
# Create table
cursor.execute("""CREATE TABLE STUDENT(NAME VARCHAR(255), CLASS VARCHAR(255), SECTION VARCHAR(255))""")
# Insert data into the table
cursor.execute("INSERT INTO STUDENT VALUES ('Raju', '7th', 'A')")
cursor.execute("INSERT INTO STUDENT VALUES ('Shyam', '8th', 'B')")
cursor.execute("INSERT INTO STUDENT VALUES ('Baburao', '9th', 'C')")
# Display inserted data
print("Data Inserted in the table: ")
cursor.execute("SELECT * FROM STUDENT")
for row in cursor.fetchall():
print(row)
# Commit changes and close connection
conn.commit()
conn.close()
Output:
SQLite3:
2. Insert Data Using Column Names and ValuesIn the second method we will specify both the columns which we want to fill and their corresponding values.
Syntax:
ExampleINSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2, value3, ...);
The below program is similar to that of the 1st program, but we insert values into the table by reordering the names of the columns with values as in the 2nd syntax.
Python
import sqlite3
# Connect to SQLite database
conn = sqlite3.connect('geek.db')
cursor = conn.cursor()
# Create table
cursor.execute("""CREATE TABLE STUDENT(NAME VARCHAR(255), CLASS VARCHAR(255), SECTION VARCHAR(255))""")
# Insert data into the table using column names
cursor.execute("INSERT INTO STUDENT (CLASS, SECTION, NAME) VALUES ('7th', 'A', 'Raju')")
cursor.execute("INSERT INTO STUDENT (SECTION, NAME, CLASS) VALUES ('B', 'Shyam', '8th')")
cursor.execute("INSERT INTO STUDENT (NAME, CLASS, SECTION) VALUES ('Baburao', '9th', 'C')")
# Display inserted data
print("Data Inserted in the table: ")
cursor.execute("SELECT * FROM STUDENT")
for row in cursor.fetchall():
print(row)
# Commit changes and close connection
conn.commit()
conn.close()
Output:
SQLite3:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4