Python insert rows into SQLite table

Inserting data into an SQLite table using Python involves several steps. First, you need to establish a connection to the SQLite database. Then, you’ll create a cursor object to interact with the database and execute SQL commands. Finally, you can use the INSERT INTO SQL statement to add data to the table.

Here’s a step-by-step guide on how to insert data into an SQLite table with Python:

Import the necessary libraries

You need to import the sqlite3 library to work with SQLite databases.

import sqlite3

Connect to the SQLite database

Create a connection to your SQLite database file using the sqlite3.connect() method. If the database file does not exist, it will be created.

# Replace 'your_database.db' with the name of your SQLite database file.
conn = sqlite3.connect('your_database.db')

Create a cursor object

Create a cursor object using the conn.cursor() method. The cursor is used to execute SQL queries.

cursor = conn.cursor()

Define your SQL INSERT statement

Create an SQL INSERT statement with the appropriate values to insert into your table. Replace table_name with the name of your table and provide the values you want to insert.

table_name = 'your_table_name'
values_to_insert = (value1, value2, value3)  # Replace with your actual values
sql_insert = f"INSERT INTO {table_name} (column1, column2, column3) VALUES (?, ?, ?)"

Note: Replace column1, column2, and column3 with the actual column names where you want to insert the values.

Execute the INSERT statement

Execute the SQL INSERT statement using the cursor.execute() method, passing the SQL statement and the values as a tuple.

cursor.execute(sql_insert, values_to_insert)

Commit the changes

After executing the INSERT statement, commit the changes to the database using the conn.commit() method.

conn.commit()

Close the database connection

To ensure that your changes are saved and to release resources, close the database connection when you’re done.

conn.close()

Here’s a complete example:

import sqlite3

# Connect to the database
conn = sqlite3.connect('your_database.db')
cursor = conn.cursor()

# Define the INSERT statement and values
table_name = 'your_table_name'
values_to_insert = ('John', 'Doe', 30)
sql_insert = f"INSERT INTO {table_name} (first_name, last_name, age) VALUES (?, ?, ?)"

# Execute the INSERT statement
cursor.execute(sql_insert, values_to_insert)

# Commit the changes and close the connection
conn.commit()
conn.close()

Make sure to replace ‘your_database.db’, ‘your_table_name’, and the column names and values with your actual database and table details.