Python Core



Admission Enquiry Form


Database Connectivity in Python

In Database Connectivity, we will learn the steps to connect the python application to the database.
There are the following steps to connect a python application to the database.
  1. Import sqlite3
  2. Create the connection object.
  3. Execute the query.

 

Example of Database insert Statement

import sqlite3 as sql
con=sql.connect("compuhelp.db")
print("database ok")
#sqlstr="create table student(stname varchar(20),strollno int(3),stfee int(5))"
#con.execute(sqlstr)
#print("Table Created Successfully")
con.execute("insert into student values('sunil',177,4500)")
con.execute("insert into student values('anil',178,4500)")
con.execute("insert into student values('shivang',179,4500)")
print("Record added to database")
con.commit()
con.close()



Output

database ok
Record added to database


Code to read data from the table

Here we will create cursor object

import  sqlite3 as sql
con=sql.connect("compuhelp.db")
mycur=con.execute("select * from student") #will create cursor
print(" Name  ","  Rollno  ","  Fee ")
for rec in mycur:
print(rec[0],"   ",rec[1],"     ",rec[2])
con.close()



Output

 Name    Rollno     Fee 
sunil      177     4500
anil       178     4500
shivang    179     4500