![]() |
VOOZH | about |
In this article, integrating SQLite3 with Python is discussed. Here we will discuss all the CRUD operations on the SQLite3 database using Python. CRUD contains four major operations -
π CRUD operations SQLite3 and Python
Note: This needs a basic understanding of SQL.
Here, we are going to connect SQLite with Python. Python has a native library for SQLite3 called sqlite3. Let us explain how it works.
import sqlite3
sqliteConnection = sqlite3.connect('gfg.db')cursor = sqliteConnection.cursor()
Output:
Connected to the database
Before moving further to SQLite3 and Python let's discuss the cursor object in brief.
After connecting to the database and creating the cursor object let's see how to execute the queries.
In this example, we will create the SQLite3 tables using Python. The standard SQL command will be used for creating the tables.
Output:
π python sqlite3 create table
To insert data into the table we will again write the SQL command as a string and will use the execute() method.
Output:
π python sqlite3 insert data
Output:
π insert into table python sqlite3
In this section, we have discussed how to create a table and how to add new rows in the database. Fetching the data from records is simple as inserting them. The execute method uses the SQL command of getting all the data from the table using βSelect * from table_nameβ and all the table data can be fetched in an object in the form of a list of lists.
Output:
π fetch data python sqlite3
Note: It should be noted that the database file that will be created will be in the same folder as that of the python file. If we wish to change the path of the file, change the path while opening the file.
For updating the data in the SQLite3 table we will use the UPDATE statement. We can update single columns as well as multiple columns using the UPDATE statement as per our requirement.
UPDATE table_name SET column1 = value1, column2 = value2,β¦ WHERE condition;
In the above syntax, the SET statement is used to set new values to the particular column, and the WHERE clause is used to select the rows for which the columns are needed to be updated.
Output:
π update sqlite3 table using Python
For deleting the data from the SQLite3 table we can use the delete command.
DELETE FROM table_name [WHERE Clause]
Output:
π Deleting from SQLite3 table using Python
DROP is used to delete the entire database or a table. It deleted both records in the table along with the table structure.
Syntax:
DROP TABLE TABLE_NAME;
Total tables in the gfg.db before dropping
π drop sqlite3 table using Python
Now let's drop the Student table and then again check the total table in our database.
Output:
π Dropping SQLite3 table using Python
Note: To learn more about SQLit3 with Python refer to our Python SQLite3 Tutorial.