The Wayback Machine - https://web.archive.org/web/20241119112847/https://www.geeksforgeeks.org/sql-using-python/
Open In App

SQL using Python

Last Updated : 03 Oct, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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. 

Connecting to SQLite Database

  • To use SQLite, we must import sqlite3.
import sqlite3
  • Then create a connection using connect() method and pass the name of the database you want to access if there is a file with that name, it will open that file. Otherwise, Python will create a file with the given name.
sqliteConnection = sqlite3.connect('gfg.db')
  • After this, a cursor object is called to be capable to send commands to the SQL. 
cursor = sqliteConnection.cursor()

Example: Connecting to SQLite3 database using Python

Python3




import sqlite3
 
# connecting to the database
connection = sqlite3.connect("gfg.db")
 
# cursor
crsr = connection.cursor()
 
# print statement will execute if there
# are no errors
print("Connected to the database")
 
# close the connection
connection.close()


Output:

Connected to the database

Cursor Object

Before moving further to SQLite3 and Python let’s discuss the cursor object in brief. 

  • The cursor object is used to make the connection for executing SQL queries.
  • It acts as middleware between SQLite database connection and SQL query. It is created after giving connection to SQLite database. 
  • The cursor is a control structure used to traverse and fetch the records of the database. 
  • All the commands will be executed using cursor object only.

Executing SQLite3 Queries – Creating Tables

After connecting to the database and creating the cursor object let’s see how to execute the queries.

  • To execute a query in the database, create an object and write the SQL command in it with being commented. Example:- sql_comm = ”SQL statement”
  • And executing the command is very easy. Call the cursor method execute() and pass the name of the sql command as a parameter in it. Save a number of commands as the sql_comm and execute them. After you perform all your activities, save the changes in the file by committing those changes and then lose the connection. 

Example: Creating SQLite3 tables using Python

In this example, we will create the SQLite3 tables using Python. The standard SQL command will be used for creating the tables.

Python




import sqlite3
 
# connecting to the database
connection = sqlite3.connect("gfg.db")
 
# cursor
crsr = connection.cursor()
 
# SQL command to create a table in the database
sql_command = """CREATE TABLE emp (
staff_number INTEGER PRIMARY KEY,
fname VARCHAR(20),
lname VARCHAR(30),
gender CHAR(1),
joining DATE);"""
 
# execute the statement
crsr.execute(sql_command)
 
# close the connection
connection.close()


Output:

python sqlite3 create table

Inserting into Table

To insert data into the table we will again write the SQL command as a string and will use the execute() method.

Example 1: Inserting Data into SQLite3 table using Python

Python3




# Python code to demonstrate table creation and
# insertions with SQL
 
# importing module
import sqlite3
 
# connecting to the database
connection = sqlite3.connect("gfg.db")
 
# cursor
crsr = connection.cursor()
 
# SQL command to insert the data in the table
sql_command = """INSERT INTO emp VALUES (23, "Rishabh",\
"Bansal", "M", "2014-03-28");"""
crsr.execute(sql_command)
 
# another SQL command to insert the data in the table
sql_command = """INSERT INTO emp VALUES (1, "Bill", "Gates",\
"M", "1980-10-28");"""
crsr.execute(sql_command)
 
# To save the changes in the files. Never skip this.
# If we skip this, nothing will be saved in the database.
connection.commit()
 
# close the connection
connection.close()


Output:

python sqlite3 insert data

Example 2: Inserting data input by the user

Python3




# importing module
import sqlite3
 
# connecting to the database
connection = sqlite3.connect("gfg.db")
 
# cursor
crsr = connection.cursor()
 
# primary key
pk = [2, 3, 4, 5, 6]
 
# Enter 5 students first names
f_name = ['Nikhil', 'Nisha', 'Abhinav', 'Raju', 'Anshul']
 
# Enter 5 students last names
l_name = ['Aggarwal', 'Rawat', 'Tomar', 'Kumar', 'Aggarwal']
 
# Enter their gender respectively
gender = ['M', 'F', 'M', 'M', 'F']
 
# Enter their joining data respectively
date = ['2019-08-24', '2020-01-01', '2018-05-14', '2015-02-02', '2018-05-14']
 
for i in range(5):
 
    # This is the q-mark style:
    crsr.execute('INSERT INTO emp VALUES ({pk[i]}, "{f_name[i]}", "{l_name[i]}", "{gender[i]}", "{date[i]}")')
 
# To save the changes in the files. Never skip this.
# If we skip this, nothing will be saved in the database.
connection.commit()
 
# close the connection
connection.close()


Output:

insert into table python sqlite3

Fetching Data

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.

Example: Reading Data from sqlite3 table using Python

Python




# importing the module
import sqlite3
 
# connect with the myTable database
connection = sqlite3.connect("gfg.db")
 
# cursor object
crsr = connection.cursor()
 
# execute the command to fetch all the data from the table emp
crsr.execute("SELECT * FROM emp")
 
# store all the fetched data in the ans variable
ans = crsr.fetchall()
 
# Since we have already selected all the data entries
# using the "SELECT *" SQL command and stored them in
# the ans variable, all we need to do now is to print
# out the ans variable
for i in ans:
    print(i)


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.

Updating Data

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. 

Example: Updating SQLite3 table using Python

Python3




# Import module
import sqlite3
 
# Connecting to sqlite
conn = sqlite3.connect('gfg.db')
 
# Creating a cursor object using
# the cursor() method
cursor = conn.cursor()
 
# Updating
cursor.execute('''UPDATE emp SET lname = "Jyoti" WHERE fname="Rishabh";''')
 
# Commit your changes in the database
conn.commit()
 
# Closing the connection
conn.close()


Output:

update sqlite3 table using Python

Deleting Data

For deleting the data from the SQLite3 table we can use the delete command. 

DELETE FROM table_name [WHERE Clause]

Example: Deleting from SQLite3 table using Python

Python3




# Import module
import sqlite3
 
# Connecting to sqlite
conn = sqlite3.connect('gfg.db')
 
# Creating a cursor object using
# the cursor() method
cursor = conn.cursor()
 
# Updating
cursor.execute('''DELETE FROM emp WHERE fname="Rishabh";''')
 
# Commit your changes in the database
conn.commit()
 
# Closing the connection
conn.close()


Output:

Deleting from SQLite3 table using Python

Deleting Table

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;

Example: Drop SQLite3 table using Python

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.

Python3




# Import module
import sqlite3
 
# Connecting to sqlite
conn = sqlite3.connect('gfg.db')
 
# Creating a cursor object using
# the cursor() method
cursor = conn.cursor()
 
# Updating
cursor.execute('''DROP TABLE Student;''')
 
# Commit your changes in the database
conn.commit()
 
# Closing the connection
conn.close()


Output:

Dropping SQLite3 table using Python

Note: To learn more about SQLit3 with Python refer to our Python SQLite3 Tutorial. 



Previous Article
Next Article

Similar Reads

Configure SQL Jobs in SQL Server using T-SQL
In this article, we will learn how to configure SQL jobs in SQL Server using T-SQL. Also, we will discuss the parameters of SQL jobs in SQL Server using T-SQL in detail. Let's discuss it one by one. Introduction :SQL Server Agent is a component used for database task automation. For Example, If we need to perform index maintenance on Production ser
7 min read
Difference between Structured Query Language (SQL) and Transact-SQL (T-SQL)
Structured Query Language (SQL): Structured Query Language (SQL) has a specific design motive for defining, accessing and changement of data. It is considered as non-procedural, In that case the important elements and its results are first specified without taking care of the how they are computed. It is implemented over the database which is drive
2 min read
How to SQL Select from Stored Procedure using SQL Server?
There may be situations in SQL Server where you need to use a stored procedure to get data from a SQL query. For direct data selection from a stored procedure within a query, SQL Server offers options like OPENQUERY and OPENROWSET. The usual way is running the stored procedure independently and then querying the outcomes. The idea of utilizing SQL
3 min read
SQL SERVER – Input and Output Parameter For Dynamic SQL
An Input Parameter can influence the subset of rows it returns from a select statement within it. A calling script can get the value of an output parameter. An aggregate function or any computational expression within the stored process can be used to determine the value of the output parameter. A parameter whose value is given into a stored proced
3 min read
Difference between T-SQL and PL-SQL
1. Transact SQL (T-SQL) : T-SQL is an abbreviation for Transact Structure Query Language. It is a product by Microsoft and is an extension of SQL Language which is used to interact with relational databases. It is considered to perform best with Microsoft SQL servers. T-SQL statements are used to perform the transactions to the databases. T-SQL has
3 min read
SQL - SELECT from Multiple Tables with MS SQL Server
In SQL we can retrieve data from multiple tables also by using SELECT with multiple tables which actually results in CROSS JOIN of all the tables. The resulting table occurring from CROSS JOIN of two contains all the row combinations of the 2nd table which is a Cartesian product of tables. If we consider table1 contains m rows and table2 contains n
3 min read
How to Execute SQL Server Stored Procedure in SQL Developer?
A stored procedure is a set of (T-SQL ) statements needed in times when we are having the repetitive usage of the same query. When there is a need to use a large query multiple times we can create a stored procedure once and execute the same wherever needed instead of writing the whole query again. In this article let us see how to execute SQL Serv
2 min read
SQL Query to Check if Date is Greater Than Today in SQL
In this article, we will see the SQL query to check if DATE is greater than today's date by comparing date with today's date using the GETDATE() function. This function in SQL Server is used to return the present date and time of the database system in a ‘YYYY-MM-DD hh:mm: ss. mmm’ pattern. Features: This function is used to find the present date a
2 min read
SQL Query to Add a New Column After an Existing Column in SQL
Structured Query Language or SQL is a standard Database language that is used to create, maintain and retrieve data from relational databases like MySQL, Oracle, SQL Server, Postgres, etc. In Microsoft SQL Server, we can change the order of the columns and can add a new column by using ALTER command. ALTER TABLE is used to add, delete/drop or modif
3 min read
SQL Query to Convert Rows to Columns in SQL Server
In this article we will see, how to convert Rows to Column in SQL Server. In a table where many columns have the have same data for many entries in the table, it is advisable to convert the rows to column. This will help to reduce the table and make the table more readable. For example, Suppose we have a table given below: NAMECOLLEGEROLL NUMBERSUB
2 min read
SQL Quiz : Practice SQL Questions Online
This SQL quiz covers various topics like SQL basics, CRUD operations, operators, aggregation functions, constraints, joins, indexes, transactions, and query-based scenarios. We've included multiple-choice questions, fill-in-the-blank questions, and interactive coding challenges to keep things interesting and challenging. Whether you're a beginner l
3 min read
BULK INSERT in SQL Server(T-SQL command)
BULK INSERT in SQL Server(T-SQL command): In this article, we will cover bulk insert data from csv file using the T-SQL command in the SQL server and the way it is more useful and more convenient to perform such kind of operations. Let's discuss it one by one.  ConditionSometimes there is a scenario when we have to perform bulk insert data from .cs
3 min read
Difference between SQL and T-SQL
SQL (Structured Query Language) is the standard language for managing and manipulating relational databases, enabling operations like querying, updating, and deleting data. T-SQL (Transact-SQL), an extension of SQL developed by Microsoft, adds advanced features and procedural capabilities specifically for SQL Server. In this article, We will learn
4 min read
SQL Server | Convert Tables in T-SQL into XML
XML (Extensible Markup Language) is a widely-used markup language designed to store and transfer structured data between different systems and platforms. While HTML focuses on the visual representation of data OverviewXML is similar to HTML which is designed to structure and store data for sharing across different systems and platforms.Unlike HTML,
3 min read
SQL Exercises : SQL Practice with Solution for Beginners and Experienced
SQL (Structured Query Language) is a powerful tool used for managing and manipulating relational databases. Whether we are beginners or experienced professionals, practicing SQL exercises is important for improving your skills. Regular practice helps you get better at using SQL and boosts your confidence in handling different database tasks. So, in
15+ min read
SQL using Python and SQLite | Set 2
Databases offer numerous functionalities by which one can manage large amounts of information easily over the web, and high-volume data input and output over a typical file such as a text file. SQL is a query language and is very popular in databases. Many websites use MySQL. SQLite is a "light" version that works over syntax very much similar to S
3 min read
SQL using Python | Set 3 (Handling large data)
It is recommended to go through SQL using Python | Set 1 and SQL using Python and SQLite | Set 2 In the previous articles the records of the database were limited to small size and single tuple. This article will explain how to write & fetch large data from the database using module SQLite3 covering all exceptions. A simple way is to execute th
4 min read
How to Find Duplicate Values in a SQL Table using Python?
MySQL server is an open-source relational database management system that is a major support for web-based applications. Databases and related tables are the main component of many websites and applications as the data is stored and exchanged over the web. In order to access MySQL databases from a web server, we use various modules in Python such a
3 min read
How to find tables that contain a specific column in SQL using Python?
MySQL server is an open-source relational database management system that is a major support for web-based applications. Databases and related tables are the main component of many websites and applications as the data is stored and exchanged over the web. In order to access MySQL databases from a web server, we use various modules in Python such a
3 min read
Count SQL Table Column Using Python
Prerequisite: Python: MySQL Create Table In this article, we are going to see how to count the table column of a MySQL Table Using Python. Python allows the integration of a wide range of database servers with applications. A database interface is required to access a database from Python. MySQL Connector-Python module is an API in python for commu
2 min read
How to read image from SQL using Python?
In this article, we are going to discuss how to read an image or file from SQL using python. For doing the practical implementation, We will use MySQL database. First, We need to connect our Python Program with MySQL database. For doing this task, we need to follow these below steps: Steps to Connect Our Python Program with MySQL: Install the MySQL
3 min read
Connecting to SQL Database using SQLAlchemy in Python
In this article, we will see how to connect to an SQL database using SQLAlchemy in Python. To connect to a SQL database using SQLAlchemy we will require the sqlalchemy library installed in our python environment. It can be installed using pip - !pip install sqlalchemyThe create_engine() method of sqlalchemy library takes in the connection URL and r
3 min read
Create a SQL table from Pandas dataframe using SQLAlchemy
In this article, we will discuss how to create a SQL table from Pandas dataframe using SQLAlchemy. As the first steps establish a connection with your existing database, using the create_engine() function of SQLAlchemy. Syntax: from sqlalchemy import create_engine engine = create_engine(dialect+driver://username:password@host:port/database) Explana
3 min read
SQL | USING Clause
If several columns have the same names but the datatypes do not match, the NATURAL JOIN clause can be modified with the USING clause to specify the columns that should be used for an EQUIJOIN. USING Clause is used to match only one column when more than one column matches. NATURAL JOIN and USING Clause are mutually exclusive. It should not have a q
2 min read
How to Execute SQL File with Java using File and IO Streams?
In many cases, we often find the need to execute SQL commands on a database using JDBC to load raw data. While there are command-line or GUI interfaces provided by the database vendor, sometimes we may need to manage the database command execution using external software. In this article, we will learn how to execute an SQL file containing thousand
5 min read
Swap two numbers in PL/SQL without using temp
In PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations. Given two numbers num1 and num2 and the task is to swap the value of given numbers. Examples: Input : num1 = 1000, num2 = 2000 Output : num1
2 min read
SQL | Checking Existing Constraints on a Table using Data Dictionaries
Prerequisite: SQL-Constraints In SQL Server the data dictionary is a set of database tables used to store information about a database's definition. One can use these data dictionaries to check the constraints on an already existing table and to change them(if possible). USER_CONSTRAINTS Data Dictionary: This data dictionary contains information ab
2 min read
Combining aggregate and non-aggregate values in SQL using Joins and Over clause
Prerequisite - Aggregate functions in SQL, Joins in SQLAggregate functions perform a calculation on a set of values and return a single value. Now, consider an employee table EMP and a department table DEPT with following structure:Table - EMPLOYEE TABLE NameNullTypeEMPNONOT NULLNUMBER(4)ENAME VARCHAR2(10)JOB VARCHAR2(9)MGR NUMBER(4)HIREDATE DATESA
2 min read
SQL using C/C++ and SQLite
In this article, we'd like to introduce the article about SQLITE combined with C++ or C. Before we go on with this tutorial, we need to follow the SQLITE3 installation procedure that can be easily found here. At the same time it is required a basic knowledge of SQL. We will show the following operations: Database Connection/Creation Create Table In
6 min read
Copy tables between databases in SQL Server using Import-and-Export Wizard
Introduction to Import-and-Export Wizard : The wizard allows easy steps through a process, and to execute the data copy process with writing very little or no code. However, for importing and exporting data from one source into another, the below steps could be followed - Open the Object Explorer, select the database, right-click on the database na
2 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg