0% found this document useful (0 votes)
15 views13 pages

Computer Science (Shreya and Sasikala)

The document provides a tutorial on using Python's sqlite3 module to manage a database, including creating tables, inserting data, and querying results. It demonstrates how to accept user input for student records, join multiple tables, and export query results to a CSV file. Additionally, it shows how to list all tables in a database and emphasizes the versatility of SQL commands within Python scripts.

Uploaded by

akshaya2445
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views13 pages

Computer Science (Shreya and Sasikala)

The document provides a tutorial on using Python's sqlite3 module to manage a database, including creating tables, inserting data, and querying results. It demonstrates how to accept user input for student records, join multiple tables, and export query results to a CSV file. Additionally, it shows how to list all tables in a database and emphasizes the versatility of SQL commands within Python scripts.

Uploaded by

akshaya2445
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 13

Data

input
by User
In this example we are going to accept data using Python input() command
during runtime and then going to write in the Table called Person.

# code for executing query using input data


import sqlite3
# creates a database in RAM
con =sqlite3.connect("Academy.db")
cur =con.cursor()
cur.execute("DROP Table person")
cur.execute("create table person (name, age, id)")
print("Enter 5 students names:")
who =[input() for i in range(5)]
print("Enter their ages respectively:")
age =[int(input()) for i in range(5)]
print("Enter their ids respectively:")
p_id =[int(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]))
cur.execute("select * from person")
# Fetches all entries from table
print("Displaying All the Records From Person Table")
Outpu
t Enter 5 students names:
RAM
KEERTHANA
KRISHNA
HARISH
GIRISH
Enter their ages respectively:
28
12
21
18
16
Enter their ids respectively:
1
2
3
4
5
Displaying All the Records From Person Table
('RAM', 28, 1)
('KEERTHANA', 12, 2)
('KRISHNA', 21, 3)
('HARISH', 18, 4)
('GIRISH', 16, 5)

You can even add records to the already existing table like
Student Using the above coding with appropriate modification in
the Field Name. To do so you should comment the create table
Using
Multiple
Table for
Queryin
g
Python allows to query more than one table by
import sqlite3 joining them. In the following example a new table
connection = sqlite3.connect("Academy.db") called Appointment which contain the details of
cursor = connection.cursor() students Rollno, Duty, Age is created. The tables
cursor.execute("""DROP TABLE Appointment;""") student and Appointment are joined and
sql_command = """ displayed the result with the column headings.
CREATE TABLE Appointment(rollnointprimarkey,Dutyvarchar(10),age
int)"""
cursor.execute(sql_command)
sql_command = """INSERT INTO Appointment (Rollno,Duty ,age )
VALUES ("1", "Prefect", "17");"""
cursor.execute(sql_command)
sql_command = """INSERT INTO Appointment (Rollno, Duty, age)
VALUES ("2", "Secretary", "16");"""
Output
cursor.execute(sql_command)
# never forget this, if you want the changes to be saved:
connection.commit()
['Rollno', 'Sname', 'Duty',
cursor.execute ("SELECT student.rollno,student.sname,
'age']
Appointment.Duty, Appointment.Age FROM
student,Appointment
(1, 'Akshay', 'Prefect', 17)
where student.rollno=Appointment.rollno")
(2, 'Aravind', 'Secretary',
#print (cursor.description) to display the field names of the table 16)
co = [i[0] for i in cursor.description]
print(co)
# Field informations can be read from cursor.description.
result = cursor.fetchall()
for r in result:
print(r)
Integratin
g Query
With Csv
File
You can even store the query result in a import sqlite3
CSV file. This will be useful to display the import io # to access replace()
query output in a tabular format. In the import csv
following example using Python script the # CREATING CSV FILE
student table is sorted gender wise in d=open('c:/pyprg/sql.csv','w')
descending order and then arranged c=csv.writer(d)
the records alphabetically. The output of connection = sqlite3.connect("Academy.db")
this Query will be written in a CSV file cursor = connection.cursor()
called SQL.CSV,again the content is read # a=Connection.cursor()
from the CSV file and displayed the cursor.execute("SELECT * FROM student ORDER BY GENDER
result. DESC,SNAME")
# WRITING THE COLUMN HEADING
co = [i[0] for i in cursor.description]
c.writerow(co)
data=cursor.fetchall()
for item in data:
c.writerow(item)
d.close()
# Reading the CSV File
# replace() is used to eliminate the newline character at the end
of each row
with open('c:/pyprg/sql.csv', "r", newline=None) as fd:
# r = csv.reader(fd)
for line in fd:
line = line.replace("\n", "")
print(line)
cursor.close()
connection.close()
Outpu
t
Rollno,Sname,Grade,gender,Average,birt
h_date
1, Akshay, B, M, 87.8, 2001-12-12
2, Aravind, A, M, 92.5, 2000-08-17
3, BASKAR, C, M, 75.2, 1998-05-17
7, TARUN, D, M, 62.3, 1999-02-01
5, VARUN, B, M, 80.6, 2001-03-14
6, PRIYA, A, F, 98.6, 2002-01-01
4, SAJINI, A, F, 95.6, 2002-11-01
Opening the file ( "sqlexcel.cs" ) through MS-
Excel and view the result
import sqlite3
import io #to access replace()
import csv
# database name to be passed as parameter
conn = sqlite3.connect("Academy.db")
print(“Content of the table before sorting and writing in CSV file”)
cursor = conn.execute("SELECT * FROM Student")
for row in cursor:
print (row)
# CREATING CSV FILE
d=open('c:\pyprg\sqlexcel.csv','w')
c=csv.writer(d)
cursor = conn.cursor()
cursor.execute("SELECT * FROM student ORDER BY GENDER
DESC,SNAME")
#WRITING THE COLUMN HEADING
co = [i[0] for i in cursor.description]
c.writerow(co)
data=cursor.fetchall()
for item in data:
c.writerow(item)
d.close()
print("sqlexcel.csv File is created open by visiting c:\pyprg\sqlexcel.csv")
conn.close()
Output
Content of the table before sorting and writing in CSV
file
(1, 'Akshay', 'B', 'M', 87.8, '2001-12-12')
(2, 'Aravind', 'A', 'M', 92.5, '2000-08-17')
(3, 'BASKAR', 'C', 'M', 75.2, '1998-05-17')
(4, 'SAJINI', 'A', 'F', 95.6, '2002-11-01')
(5, 'VARUN', 'B', 'M', 80.6, '2001-03-14')
(6, 'Priyanka', 'A', 'F', 98.6, '2002-01-01')
(7, 'TARUN', 'D', 'M', 62.3, '1999-02-01')
sqlexcel.csv File is created open by visiting c:\pyprg\
sqlexcel.csv
Output Through
Excel
Table
List
To show (display) the list of tables created in a database
the following program can be used.

import sqlite3
con = sqlite3.connect('Academy.db')
cursor = con.cursor()
cursor.execute("SELECT name FROM
sqlite_master WHERE type='table';")
print(cursor.fetchall())

Output
[('Student',), ('Appointment',),
('Person',)]

The above program display the names of all tables created in 'Academy. db' database. The
master table holds the key information about your database tables and it is called
sqlite_master.

So far, you have been using the Structured Query Language in Python scripts. Almost all sql
commands can be executed by Python SQLite module. You can even try the other commands
THANK YOU!
Presentation By Sasikala and
Shreya

You might also like