Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 9

Module:Database Access

Connecting to the database


 import sqlite3
db_conn = sqlite3.connect(‘abc.db’)
print “connection established”

 connect(): return connection object & create database file abc.db in the current
directory if it is doesn’t exist.

 In order to execute any SQL statements ,we create cursor object & pass them to
cursor object to execute them.
Create table

 import sqlite3
con = sqlite3.connect('abc.db')

c=con.cursor()

c.execute('''CREATE TABLE emp


(name text, age int , salary real)''')

c.execute("INSERT INTO emp VALUES ('Ravi',23,12300.50)")

con.commit()
con.close()
Insert data
 import sqlite3
con = sqlite3.connect(‘abc.db’)
c = con.cursor()

c.execute("INSERT INTO emp VALUES ('John',24,12400.50)")


c.execute("INSERT INTO emp VALUES (‘kavi',29,12400)")
c.execute("INSERT INTO emp VALUES (‘hari',26,12700)")

con.commit()

con.close()
Retrieving Data with SQLite

 import sqlite3
con = sqlite3.connect(‘abc.db’)
c = con.cursor()
c.execute(‘’’ SELECT * FROM emp ‘’’)
emp1 = c.fetchall()
for i in emp1:
print “name = “,i[0]
print “age = “,i[1]
print “salary = “,i[2]
print “\n”
con.close()
Updating data
 Where clause is used to specify a condition

 import sqlite3
con = sqlite3.connect('abc.db')

c=con.cursor()
c.execute("UPDATE emp SET name = 'mohan' where age=23")
con.commit()
c.execute('''SELECT * FROM emp ''')
emp1 = c.fetchone()
print "name = %s"%emp1[0]
print "age = %d"%emp1[1]
print "salary= %f"%emp1[2]
con.close()
Deleting data
 import sqlite3
con = sqlite3.connect('abc.db')
c=con.cursor()
c.execute('''DELETE from emp where name = 'mohan' ''')
con.commit()
c.execute('''SELECT * FROM emp''')
emp2 = c.fetchall()
for i in emp2:
print "name = %s"%i[0]
print "age = %d"%i[1]
print "salary= %f"%i[2]
con.close()
AND & OR clause
 import sqlite3
con = sqlite3.connect('abc.db')
c=con.cursor()
#c.execute('''SELECT * FROM emp where age > 38 AND salary > 15000''')
c.execute('''SELECT * FROM emp where age > 38 OR salary > 15000''')
emp2 = c.fetchall()
for i in emp2:
print "name = %s"%i[0]
print "age = %d"%i[1]
print "salary= %f"%i[2]
print "\n"
con.close()
Order by clause
 is used to sort the data in ascending or descending order on the basis of one
or more columns..
 import sqlite3
con = sqlite3.connect('abc.db')
c=con.cursor()
c.execute('''SELECT * FROM emp order by salary ASC''')
#c.execute('''SELECT * FROM emp order by salary DESC''')
emp2 = c.fetchall()
for i in emp2:
print "name = %s"%i[0]
print "age = %d"%i[1]
print "salary= %f"%i[2]
print "\n"
con.close()

You might also like