Hello everyone, in this article, we shall study how the Sqlite3 database works and how to add multiple rows at once using Python. Now a database works on four fundamental operations CRUD.
The most in-use type of DB’s today in technological fields is Relational Databases. Their name itself defines their functioning – Tables that are connected with some special keys. One of them is the Sqlite3 database.
SQL vs SQLite3
Let’s quickly compare what SQL and SQLite have similar and different to each other.
What is SQL?
SQL is a language that helps us to communicate with our databases. The commands of SQL are specifically called “Queries”. Each query is for a special purpose. This interpreted language does not have any special compiler, rather it executes it from special SQL frameworks. There are various servers out there available on the internet. One of them is SQLite3.
What is SQLite3?
SQLite3 framework is a lightweight server for SQL. Here are some features of SQLite3.
- Does not require a server connection for raw working.
- Requires less memory space.
- No installation is necessary, extract the zip file, and it is ready for use.
- Commands are easier to execute.
- Cross-platform – runs on Windows, Linux, and Mac systems.
- Integrated – can be operated using languages like C/C++, Java, Python, etc.
Steps to Insert multiple records in Sqlite3 database
This section of the article tells us about how we can use SQLite3 with Python and add multiple records in one single command in SQL.
Note: Skip to point #5 for the code to add multiple records in an SQLite3 database using Python.
1. Setting up the environment
We need to set up some points when we work with any database. This is a good practice when working with huge projects.
- Create a folder SQLITE that will hold all our databases and codes.
- In that folder create another folder as a database. This will contain all the databases.
- Download the slqite3 zip packet from the official website: https://sqlite.org/download.html and search for the Precompiled binaries for Windows. We can choose it according to our system whether it is 32 bit or 64 bit.
- Once downloaded extract the zip file into our SQLite folder. That’s done no need to install anything.
- Create a python file data.py that contains the whole code we will write.
It will look like this now:
2. Creating a database in SQLite3 using Python
Python provides a special library namely sqlite3 which comes as a built-in package along with it. So, our task becomes easy. We just need to have Python 3.x.x version in our system. It is a recommendation to use 3.6.x versions for error-free programming.
import sqlite3 connection = sqlite3.connect('databases/student.db') # file path # create a cursor object from the cursor class cur = connection.cursor() cur.execute(''' CREATE TABLE customers( first_name text, last_name text, email text )''') # committing our connection connection.commit() # close our connection connection.close()
DATA TYPES IN SQLITE: There are five types of datatypes present in sqlite3
- REAL: decimal point digit
- TEXT: string
- Blob: images, mp3 file, video file etc.
- Import the sqlite3 module.
- Create a connection object using the connect() method. This method creates a database. Store this using a connection object.
- Create a cursor object using the cursor() function. Create a simple object for an easy workflow. The cursor object helps to connect to a new or existing database and perform operations on it.
- Then using the same cursor object call the execute() function. This function takes all the SQL queries in the form of string arguments.
- Create a simple database that holds three records ‘first_name’, ‘last_name’, and ’email’. Commit the action using commit() function. Call it with the connection object using the dot “.” operator.
- Close the connection using the close() method.
This command also inserts a “student.db” file into the database folder.
3. View the database in SQLite studio
Open the SQLite studio from the extracted zip folder and select the language as “American English”. Then, it will open an interface like this:
Click on the Database column and select Add a database option from it. We can also perform it using the “Ctrl + O” command.
4. Inserting values into the database
This is one of the most important queries. Because there is no benefit of creating a table and leaving it empty. So, we will insert some sample data into our table. The SQLite module’s two methods provide us with help for doing the same.
- execute() – inserts only one record at a time.
- executemany() – inserts many records at a time.
Adding one record at a time
import sqlite3 connection = sqlite3.connect('databases/student.db') # file path # create a cursor object from the cursor class cur = connection.cursor() cur.execute("INSERT INTO student_data VALUES ('Shree', 'Narayan', '[email protected]')") # committing our connection print('Command executed successfully!!!') connection.commit() # close our connection connection.close()
To view the change in our database just open the Sqlite3 studio and view the Data option of the studio.
- First, connect with the database.
- Then create a cursor object.
- Then add the record of student having name = “Shree”, last_name = “Narayan” and email = “[email protected]” using the execute() function.
- Commit the changes and then close the connection.
5. Adding multiple records at a time
import sqlite3 # connection = sqlite3.connect(':memeory:') connection = sqlite3.connect('databases/student.db') # file path # create a cursor object from the cursor class cur = connection.cursor() # creating a list of items multiple_columns = [('Walt', 'Diseny', '[email protected]'), ('Ben', 'Parker', '[email protected]'), ('Charlemagne', 'Butler', '[email protected]')] cur.executemany("INSERT INTO student_data VALUES (?,?,?)", multiple_columns) # committing our connection print('Command executed successfully!!!') connection.commit() # close our connection connection.close()
- First, connect with the database.
- Then create a cursor object.
- We need to create a list of tuples that holds data of three students. Name it multiple_records.
- Using the cursor object we will use the executemany() function. Using the (INSERT INTO student_data column VALUES (?, ?, ?), multiple_records) command.
- Here (?, ?, ?) is a placeholder that has question marks that are used according to the number of columns the particular table has. We have three columns so we use three placeholders.
Syntax of executemany() function:
cursor_object.executemany("INSERT INTO database_name VALUES (?,?,?,...?)", column_list)
Go to the studio and then click on the refresh button or press F5, we get the updated student_data.
Here we wrap up this article, I hope this helps everyone in making all the possible changes in their respective DBMS. SQLite with Python is easy to learn but revise this concerning every piece of code.