Unit-7 Working With Databases
Unit-7 Working With Databases
Note: TCL commands like commit & rollback works with DML commands only
MySQL database
• MySQL is one of the widely used database. Unlike SQLite, MySQL is an external database,
and it creates a database server. To use it thorough python program we need following
softwares:
1) Python 3.6 or later: Add ‘path’ of your ‘python.exe’ file using ‘Environment Variables’
otherwise, you won’t be able to install MySQL.
2) mysql-connector-python
Python needs MySQL driver to access MySQL database, which is named as: mysql-
connector-python. To download & install driver, open windows command prompt and write:
python -m pip install mysql-connector-python
Remember, your system must be connected with internet to install above driver.
3) MySQL database:
We will use web version of MySQL database. Download and install XAMPP distribution from
following link to use web MySQL:
https://downloadsapachefriends.global.ssl.fastly.net/7.3.27/xampp-windows-x64-7.3.27-1-VC15-installer.exe?from_af=true
Cntd…
• After installing xampp distribution, open XAMPP control panel from start menu.
• Start “Apache” and “MySQL” server by clicking on “Start” button.
• Now, open any web browser and type following link:
http://127.0.0.1/dashboard/
• Click on “phpMyAdmin” residing on top right corner to open MySQL database. This is
homepage of web MySQL database.
• To verify, installation of MySQL and mysql-connector-python, write following lines in
python IDLE shell:
>>> import mysql.connector
>>>mysql.connector.connect(host=‘localhost’, user=‘root’, password=‘’)
• If there is no error, means python and MySQL connection is established.
Steps to connect python application with MySQL database
1) Import mysql.connector module
2) Create the connection object with appropriate parameters.
3) Using connection object, create cursor object.
4) With the help of cursor object, call execute or executemany method to
perform SQL statements.
5) Close connection object
Create database
import mysql.connector
mycon=mysql.connector.connect(host='localhost',user='root',password=‘Nilesh@
6’)
cur=mycon.cursor()
Output:
cur.execute('show databases') ('information_schema',)
for x in cur: ('mysql',)
('performance_schema',)
print (x) ('sys',)
-------------------------------------------
cur.execute('create database test') ('information_schema',)
cur.execute('show databases') ('mysql',)
('performance_schema',)
for x in cur: ('sys',)
print (x) ('test’,)
Create operation
• Consider following code which creates ‘employee’ table in ‘test’ database.
import mysql.connector
con=mysql.connector.connect(host='localhost',database='test',user='root',password='
Nilesh@6 ')
cur=con.cursor()
cur.execute('create table employee(id int primary key, name varchar(20) not null,salary
float)')
cur.execute('show tables')
for i in cur:
print(i)
con.close()
Output: ('employee',)
Insert operation
import mysql.connector
con=mysql.connector.connect(host='localhost',database='test',user='root',password='Nilesh@6')
cur=con.cursor()
cur.execute('insert into employee values(101,"Arbaz",28000.65)')
cur.execute('insert into employee values(102,%s,30000.24)',("Rupesh",))
cur.execute('insert into employee values(%s,%s,%s)',(103,'john',25000.52))
val=[(105,"hiren",27750.38),(107,"arpan",22370.81)]
cur.executemany('insert into employee values(%s,%s,%s)',val)
con.commit()
print(cur.rowcount,"rows inserted")
con.close()
Output:
2 rows inserted
Important Point
• The mysql.connector module uses ‘%s’ as the placeholder to escape values in
any SQL statement. For example,
cursor.execute(‘insert into employee values (%s,%s), (102, ‘arpit’)’)
• You can see that, 102 is an integer, but ‘%s’ is used for it, because here ‘%s’ is
a placeholder and NOT a format specifier.
• In python ‘%s’ is a format specifier. For example,
print(‘Hello, my name is %s and I am %d year old’ %(‘amar’,22))
• You can see here, for integer value ‘%d’ is used.
• That means, whenever you are writing SQL statement for MySQL, consider
‘%s’ as place holder and whenever you are writing python code ‘%s’ works as
format specifier.
Select operation
• Example-1:
import mysql.connector
con=mysql.connector.connect(host='localhost',database='test',user='root',password='Nilesh@6')
cur=con.cursor()
cur.execute('select * from employee')
Output:
firstrow=cur.fetchone() First row is: (101, 'Arbaz', 28000.7)
print('First row is:',firstrow) (102, 'Rupesh', 30000.2)
result=cur.fetchall() (103, 'john', 25000.5)
for i in result: (105, 'hiren', 27750.4)
print (i)
(107, 'arpan', 22370.8)
cur.execute('select id,salary from employee')
con.commit()
con.close()
Cntd…
• Example-2:
import mysql.connector
con=mysql.connector.connect(host='localhost',database='test',user='root',password='Nilesh@6')
cur=con.cursor()
cur.execute('select id,name from employee where name like "a%"')
firstrow=cur.fetchone()
print('First row of result:',firstrow)
result=cur.fetchall() Output:
for row in result: First row of result: (101, 'Arbaz')
print ('%d %s'%(row[0],row[1])) 107 arpan
con.commit()
con.close()
Update operation
• Example:
import mysql.connector
con=mysql.connector.connect(host='localhost',database='test',user='root',password='Nilesh@6')
cur=con.cursor()
cur.execute('update employee set name="tarun" where id=103')
sql='update employee set name=%s where id=%s'
val=("naman",105)
cur.execute(sql,val)
print(cur.rowcount,"row affected")
con.commit()
con.close()
Output:
1 row affected
Delete operation
• Example:
import mysql.connector
con=mysql.connector.connect(host='localhost',database='test',user='root',password='Nilesh@6')
cur=con.cursor()
cur.execute('delete from employee where id in (101,105)')
print(cur.rowcount,"row deleted")
sql='delete from employee where name=%s'
val=('tarun',)
cur.execute(sql,val)
con.commit()
con.close()
Output: 2 row deleted (It shows statistics about first delete operation)
Drop table and Join operation
import mysql.connector
con=mysql.connector.connect(host='localhost',database='test',user='root',password='Nilesh@6')
cur=con.cursor()
cur.execute('drop table employee')
cur.execute('create table emp (id int primary key, name text)')
cur.execute('create table person (name varchar (20) primary key, city varchar(20))')
val=[(101,'ashish'),(103,'laxman'),(104,'arjun')]
cur.executemany('insert into emp values(%s,%s)',val)
temp=[('supan','Ahmedabad'),('ashish','Mumbai'),('vishwa','Delhi')]
cur.executemany('insert into person values(%s,%s)',temp)
cur.execute('select e.id,e.name,p.city from emp e join person p on e.name=p.name')
m=cur.fetchall()
for row in m:
print(row) Output:
con.commit() (101, 'ashish', 'Mumbai')
Limit operation
• You can limit the number of records returned from the query, by using "LIMIT" statement. For Example,
import mysql.connector
con=mysql.connector.connect(host='localhost',database='test',user='root',password='Nilesh@6')
cur=con.cursor()
cur.execute('create table emp1 ( id int, name text)')
temp=[(101,'ashish'),(103,'laxman'),(104,'arjun'),(102,'karan'),(105,'irfan'),(106,'Reema'),(108,'Advait'),
(107,'rushi')]
cur.executemany('insert into emp1 values(%s,%s)',temp)
cur.execute('select * from emp1 limit 5')
Output:
m=cur.fetchall() (101, 'ashish')
for row in m: (103, 'laxman')
print(row) (104, 'arjun')
con.commit() (102, 'karan')
con.close() (105, 'irfan')
Cntd…
• If you want to return five records, starting from the third record, you can use the "OFFSET"
keyword. For example, (Considering previous table ‘emp1’)
import mysql.connector
con=mysql.connector.connect(host='localhost',database='test',user='root',password='Nilesh@6')
cur=con.cursor()
cur.execute('select * from emp1 limit 5 offset 2')
m=cur.fetchall()
for row in m: Output:
print(row) (104, 'arjun')
con.commit() (102, 'karan')
con.close() (105, 'irfan')
(106, 'Reema')
(108, 'Advait')
Tkinter and MySQL Database Connectivity Example-1
• Example:
import mysql.connector
Output:
from tkinter import *
top=Tk()
top.geometry("300x200")
lb=Label(text="User login")
lb.grid(row=0,column=1)
lb2=Label(text="Username: ")
lb2.grid(row=2,column=0)
en1= Entry(top)
en1.grid(row=2,column=1)
lb3=Label(text="Password: ")
lb3.grid(row=3,column=0)
en2= Entry(top)
en2.grid(row=3,column=1)
def save():
m=en1.get();n=en2.get()
con=mysql.connector.connect(host='localhost',database=‘test',user='root',password='Nilesh@6')
cur=con.cursor()
cur.execute('create table if not exists userlogin (username text, password char(20))')
cur.execute('select * from userlogin')
temp=cur.fetchall()
first=[x[0] for x in temp]
if m in first:
cur.execute('update userlogin set password=%s where username=%s',(n,m))
else:
cur.execute('insert into userlogin values (%s,%s)',(en1.get(),en2.get()))
con.commit()
con.close()
b=Button(text="save",command=save)
b.grid(row=4,column=1)
mainloop()
Combobox widget of ttk (Themed Tkinter)
• Combobox is a drop down list, which can hold multiple values and show one item at a time.
Combobox is useful for select one option in many choice.
• Combobox widget is a class of ttk module of tkinter library, so you need to import this module. Let’s
take an example,
from tkinter import * Output:
from tkinter import ttk
top= Tk()
top.geometry("400x200")
lbl= Label(text="Select subject name: ")
lbl.grid(row=0,column=0)
language=["Python","Java","C++","C"] #Tuple can also be used
cb=ttk.Combobox(top,values=language)
cb.current(2) # Default selected item is at index 1
cb.grid(row=0,column=1)
mainloop()
Tkinter and MySQL Database Connectivity Example-2
import mysql.connector
from tkinter import *
from tkinter import ttk
Output:
top=Tk()
top.geometry("400x300")
lb=Label(text="Curriculum Feedback")
lb.grid(row=0,column=1)
lb1=Label(text="Name: ")
lb1.grid(row=2,column=0)
en1= Entry(top)
en1.grid(row=2,column=1)
lb2=Label(text="branch: ")
lb2.grid(row=3,column=0)
branch=StringVar(top,"CE")
rb1=Radiobutton(top,text="CE",variable=branch,value="CE")
rb1.grid(row=3,column=1,sticky=W)
rb2=Radiobutton(top,text="IT",variable=branch,value="IT")
rb2.grid(row=3,column=2,sticky=W)
lb3=Label(text="Choose Subject: ")
lb3.grid(row=5,column=0) (code continue on next slide)
subjects=["Python","ADT", "OS","Maths","DAA"]
cb=ttk.Combobox(top,values=subjects)
cb.current(0)
cb.grid(row=5,column=1)
lb4=Label(text="Feedback: ")
lb4.grid(row=6,column=0)
my_scale=IntVar()
sc= Scale(top,from_=0,to=10,variable=my_scale,orient=HORIZONTAL)
sc.grid(row=6,column=1,columnspan=2,sticky=W,pady=20)
lb5=Label(text="Comments: ")
lb5.grid(row=7,column=0)
t1=Text(top,width=15,height=3)
t1.grid(row=7,column=1)
def save():
m=en1.get(); n=branch.get(); o= cb.get(); p=my_scale.get(); q=t1.get("1.0",END)
con=mysql.connector.connect(host='localhost',database='test',user='root',password='Nilesh@6')
cur=con.cursor()
cur.execute('create table if not exists cur_feedback (name char(10) primary key, branch char(2), subject varchar(10),feedback real,comment text)')
cur.execute('insert into cur_feedback values (%s,%s,%s,%s,%s)',(m,n,o,p,q))
con.commit()
con.close()
b=Button(text="save",command=save)
b.grid(row=8,column=1)
Tkinter & Sqlite3 Database connectivity
• Example:
import sqlite3
from tkinter import * Output:
top=Tk()
top.geometry("300x200")
lb=Label(text="User login")
lb.grid(row=0,column=1)
lb2=Label(text="Username: ")
lb2.grid(row=2,column=0)
en1= Entry(top)
en1.grid(row=2,column=1)
lb3=Label(text="Password: ")
lb3.grid(row=3,column=0)
en2= Entry(top)
en2.grid(row=3,column=1)
def save():
m=en1.get();n=en2.get()
con=sqlite3.connect('test.db')
cur=con.cursor()
cur.execute('create table if not exists userlogin (username text, password char(20))')
cur.execute('select * from userlogin')
temp=cur.fetchall()
first=[x[0] for x in temp]
if m in first:
cur.execute('update userlogin set password=? where username=?',(n,m))
else:
cur.execute('insert into userlogin values (?,?)',(en1.get(),en2.get()))
con.commit()
con.close()
b=Button(text="save",command=save)
b.grid(row=4,column=1)
mainloop()