SQL using Python and SQLite | Set 2
Last Updated :
06 Feb, 2018
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 SQL.
SQLite is a self-contained, high-reliability, embedded, full-featured, public-domain, SQL database engine. It is the most used database engine in the world wide web.
Python has a library to access SQLite databases, called sqlite3, intended for working with this database which has been included with Python package since version 2.5.
In this article we will discuss, how to query database using commands like Update and Delete and also to visualize data via graphs.
It is recommended to go through
SQL using Python | Set 1
Updation and Deletion Operation
Python
# code for update operation
import sqlite3
# database name to be passed as parameter
conn = sqlite3.connect('mydatabase.db')
# update the student record
conn.execute("UPDATE Student SET name = 'Sam' where unix='B113059'")
conn.commit()
print "Total number of rows updated :", conn.total_changes
cursor = conn.execute("SELECT * FROM Student")
for row in cursor:
print row,
conn.close()
Output:
Total number of rows updated : 1
(u'B113053', u'Geek', u'2017-01-11 13:53:39', 21.0),
(u'B113058', u'Saan', u'2017-01-11 13:53:39', 21.0),
(u'B113059', u'Sam', u'2017-01-11 13:53:39', 22.0)
Python
# code for delete operation
import sqlite3
# database name to be passed as parameter
conn = sqlite3.connect('mydatabase.db')
# delete student record from database
conn.execute("DELETE from Student where unix='B113058'")
conn.commit()
print "Total number of rows deleted :", conn.total_changes
cursor = conn.execute("SELECT * FROM Student")
for row in cursor:
print row,
conn.close()
Output:
Total number of rows deleted : 1
(u'B113053', u'Geek', u'2017-01-11 13:53:39', 21.0),
(u'B113059', u'Sam', u'2017-01-11 13:53:39', 22.0)
Data input by User
Python
# code for executing query using input data
import sqlite3
# creates a database in RAM
con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.execute("create table person (name, age, id)")
print ("Enter 5 students names:")
who = [raw_input() for i in range(5)]
print ("Enter their ages respectively:")
age = [int(raw_input()) for i in range(5)]
print ("Enter their ids respectively:")
p_id = [int(raw_input()) for i in range(5)]
n = len(who)
for i in range(n):
# This is the q-mark style:
cur.execute("insert into person values (?, ?, ?)", (who[i], age[i], p_id[i]))
# And this is the named style:
cur.execute("select * from person")
# Fetches all entries from table
print cur.fetchall()
Output:
(u'Navin', 34, 113053)
(u'Basu', 42, 113058)
(u'Firoz', 65, 113059)
(u'Tim', 47, 113060)
(u'Varun', 54, 113061)
Graphing with SQLite
Python
# graph visualization using matplotlib library
import matplotlib.pyplot as plt
def graph_data(p_id,age):
# plotting the points
plt.plot(p_id, age, color='yellow', linestyle='dashed', linewidth = 3,
marker='*', markerfacecolor='blue', markersize=12)
# naming the x axis
plt.xlabel('Persons Id')
# naming the y axis
plt.ylabel('Ages')
# plt.plot(p_id,age)
plt.show()
print ("Enter 5 students names:")
who = [raw_input() for i in range(5)]
print ("Enter their ages respectively:")
age = [int(raw_input()) for i in range(5)]
print ("Enter their ids respectively:")
p_id = [int(raw_input()) for i in range(5)]
# calling graph function
graph_data(p_id,age)
In this way we can perform such operations using SQL query to communicate with Database and plot a Graph significantly to draw out its characteristic.
SQL using Python | Set 1
SQL using Python | Set 3 (Handling large data)
Similar Reads
How to Read Image in SQLite using Python? This article shows us how to use the Python sqlite3 module to read or retrieve images that are stored in the form of BLOB data type in an SQLite table. First, We need to read an image that is stored in an SQLite table in BLOB format using python script and then write the file back to any location on
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 cove
4 min read
SQL using Python 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 - Note: This needs a basic understanding of SQL. Here, we are going to connect SQLite with Python. Python has a nati
7 min read
How to Execute a Script in SQLite using Python? In this article, we are going to see how to execute a script in SQLite using Python. Here we are executing create table and insert records into table scripts through Python. In Python, the sqlite3 module supports SQLite database for storing the data in the database. Approach Step 1: First we need to
2 min read
How to Insert Image in SQLite using Python? In this article, we will discuss how to insert images in SQLite using sqlite3 module in Python. Implementation: 1. Set the connection to the SQLite database using Python code. sqliteConnection = sqlite3.connect('SQLite_Retrieving_data.db') cursor = sqliteConnection.cursor() 2. We need to define an I
2 min read
How to Alter a SQLite Table using Python ? In this article, we will discuss how can we alter tables in the SQLite database from a Python program using the sqlite3 module. We can do this by using ALTER statement. It allows to: Add one or more column to the tableChange the name of the table.Adding a column to a table The syntax of ALTER TABLE
3 min read
Python SQLite - Update Data In this article, we will discuss how we can update data in tables in the SQLite database using Python - sqlite3 module. The UPDATE statement in SQL is used to update the data of an existing table in the database. We can update single columns as well as multiple columns using UPDATE statement as per
7 min read
How to list tables using SQLite3 in Python ? In this article, we will discuss how to list all the tables in the SQLite database using Python. Here, we will use the already created database table from SQLite. We will also learn exception handling during connecting to our database. Database Used: Â Steps to Fetch all tables using SQLite3 in Pytho
2 min read
Using SQLite Aggregate functions in Python In this article, we are going to see how to use the aggregate function in SQLite Python. An aggregate function is a database management function that groups the values of numerous rows into a single summary value. Average (i.e., arithmetic mean), sum, max, min, Count are common aggregation functions
3 min read
Python SQLite - Select Data from Table In this article, we will discuss, select statement of the Python SQLite module. This statement is used to retrieve data from an SQLite table and this returns the data contained in the table. In SQLite the syntax of Select Statement is: SELECT * FROM table_name; * Â : means all the column from the tab
3 min read