Adding Data to SQLite with Python


Do you need to add data to your SQLite database inside your Python project?

Do you have a DataFrame in your Python project, or do you want to add the data manually? Check out this post here called Pandas DataFrame to SQLite.

Would you like to use an INSERT INTO statement in Python to put your data into a SQLite database? Let’s create a project to do this. My Python project is called Python Insert Into SQLite. We are going to ask the user at run time. I will respond with Jane Foster and Researcher.

# what if we got the data from the user?

name = input("Name? ")
position = input("Position? ")

connection = sqlite3.connect('D:\Test\emp.db')
cursor = connection.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS Employees
               (Emp_Id INT, Name TEXT, Position TEXT)''')
cursor.execute('''INSERT INTO Employees (Emp_Id, Name, Position) VALUES(?,?,?)''', (5, name, position))
connection.commit()
connection.close()

Name? Jane Foster
Position? Researcher

Using the syntax with the question marks help prevent SQL injection attacks.

What if we wanted to enter in several at the same time? We still are doing this manually in Python code.

# what if we want to enter many at a time

connection = sqlite3.connect('D:\Test\emp.db')
cursor = connection.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS Employees
               (Emp_Id INT, Name TEXT, Position TEXT)''')
# let's create a list of tuples...
# square brackkets create lists and paremtheses create tuples
employee_list = [(6, 'Herbert', 'Boot Salesman'),
                 (7, 'Rosemary', 'Architect')]
cursor.executemany('''INSERT INTO Employees (Emp_Id, Name, Position) VALUES(?,?,?)''', employee_list)
connection.commit()
connection.close()

We use executemany instead of execute.

Leave a Reply