9951 explained code solutions for 126 technologies


sqliteHow do I insert data into a SQLite database?


To insert data into a SQLite database, follow the steps below:

  1. Connect to the SQLite database using the sqlite3 Python module.
import sqlite3

connection = sqlite3.connect("mydatabase.db")
cursor = connection.cursor()
  1. Create a SQL statement to insert the data into the table.
sql_statement = "INSERT INTO users (name, email) VALUES (?, ?)"
  1. Execute the statement with the data to be inserted.
cursor.execute(sql_statement, ("John Doe", "[email protected]"))
  1. Commit the changes to the database.
connection.commit()
  1. Close the connection to the database.
connection.close()

For more information, see the SQLite Documentation and the Python SQLite3 Tutorial.

Edit this code on GitHub