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
Python Tutorial | Learn Python Programming Language Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
SQL Interview Questions Are you preparing for a SQL interview? SQL is a standard database language used for accessing and manipulating data in databases. It stands for Structured Query Language and was developed by IBM in the 1970's, SQL allows us to create, read, update, and delete data with simple yet effective commands.
15+ min read
SQL Tutorial SQL is a Structured query language used to access and manipulate data in databases. SQL stands for Structured Query Language. We can create, update, delete, and retrieve data in databases like MySQL, Oracle, PostgreSQL, etc. Overall, SQL is a query language that communicates with databases.In this S
11 min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
SQL Joins (Inner, Left, Right and Full Join) SQL joins are fundamental tools for combining data from multiple tables in relational databases. Joins allow efficient data retrieval, which is essential for generating meaningful observations and solving complex business queries. Understanding SQL join types, such as INNER JOIN, LEFT JOIN, RIGHT JO
6 min read
TCP/IP Model The TCP/IP model (Transmission Control Protocol/Internet Protocol) is a four-layer networking framework that enables reliable communication between devices over interconnected networks. It provides a standardized set of protocols for transmitting data across interconnected networks, ensuring efficie
7 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read