8 Database
8 Database
1
Python | CCIT
Table of Contents
Database ............................................................................... 3
Database ............................................................................. 3
MySQL Driver/Connector ................................................... 3
PIP ........................................................................................ 3
Class MySQLConnection ..................................................... 4
Class MySQLCursor .............................................................. 6
Database Table .................................................................. 10
Examples .......................................................................11-20
2
Python | CCIT
Database
To connect with any database we require a Connector /Driver.
Python provides us different connectors for different databases.
Such as
1. MySQL
2. Microsoft SQL Server
3. Oracle
4. SqlLite
5. Sybase
MySQL Driver/Connector
Python needs a MySQL driver to communicate with MySQL server.
We have to Download MySQL Driver/Connector.
To Install My-SQL Connector use PIP tool.
pip install mysql-connector
This Connector /Driver is defined in package mysql
PIP
pip is the standard package manager for Python.
It allows you to install and manage additional packages that are not part of
the Python standard library.
This tool is by default installed with python.
This pip tool can be executed from command prompt.
For ex: To install a package
pip install mysql-connector
For ex: To uninstall a package
pip uninstall numpy
For ex: To show list of installed packages
pip list
3
Python | CCIT
Class MySQLConnection
This class is used to manage session with database.
It is defined in module mysql.connector
Constructor:
MySQLConnection(**kwargs)
o Will connect with database and return a Connection Object if
successful.
o Arguments can be
o user : The user name used to authenticate
o password : password to authenticate the user
o database : database name
o host : The host name or IP address (default is localhost )
o port : The TCP/IP port of the MySQL server(default is 3306)
4
Python | CCIT
Methods:-
close()
o will close connection with database.
rollback()
o commits the current transaction.
close()
o Cancels the current transaction.
Is connected()
o It returns True when the connection is available, False otherwise.
cursor()
o This method returns a MySQLCursor() object.
o This Object can be used to send SQL statements to database.
Create a database ccitdb. In that data base create a table accmaster with
columns accno,name and balance. Add 4-5 records in that table accmaster.
Start mysql client command line tool.
It will ask for password:
Provide password given while installation.
If password not given then just press enter key.
Class MySQLCursor
It is used to send a sql statement to database.
MySQL cursor is read-only and non-scrollable.
Read-only
o You cannot update data in the underlying table through the cursor.
Non-scrollable
o You can only fetch rows in the order determined by the SELECT
statement.
o You cannot fetch rows in the reversed order.
o You cannot skip rows or jump to a specific row in the result set.
6
Python | CCIT
Constructor:
MySQLCursor(MySQLConnection )
o Creates a cursor from a connection object.
Methods:-
execute(query, params=None)
o This method executes the given query or command.
o For insert / update / delete operation we can check how many rows
affected by using cursor property rowcount.
o The params argument is used to pass parameter values of the query.
fetchone( )
o This method return one single record as list.
fetchall()
o This method return all records as multidimensional list.
fetchmany(SIZE)
o This method return specific number of records.
Properties:
rowcount
o Indicates no of rows affected
with_rows
o returns True or False to indicate whether the most recently executed
operation produced rows.
WAP to insert a record into table accmaster. Database=ccitdb user=root
password=admin.
cur=mydb.cursor()
cur.execute(smt)
if cur.rowcount==1:
print("Record Inserted...")
mydb.commit()
mydb.close()
except Error as e:
print("Failed to Connect",e)
mydb.commit()
mydb.close()
except Exception as e:
print("Failed to Connect",e)
WAP to read accno, name and balance and add a record into accmaster table.
conn.close()
except Exception as e:
print("Error:",e)
Database Table
create table employee(empno int,name varchar(100),job varchar(100),salary
int,joindate date);
insert into employee values(1001, 'Amit Jain', 'clerk', 25000, '2012-2-12');
insert into employee values(1002, 'Sumit Kumar', 'Manager', 50000, '2012-4-
2');
insert into employee values(1003,'Raj Rathi', 'clerk', 25000, '2014-8-22');
WAP to read accno and amt and perform deposit operation on accmaster table.
database=ccitdb user=root password=admin.
import mysql.connector as sql
try:
an=input("Enter accno:")
amt=input("Enter amount:")
conn=sql.connect(database="ccitdb",user="root",password=
"admin")
cmd="update accmaster set balance=balance+"+amt+" where
accno="+an
10
cur=conn.cursor()
Python | CCIT
cur.execute(cmd)
if cur.rowcount==1:
print("amount deposited..")
conn.commit()
else:
print("AccNo not found..")
conn.close()
except Exception as e:
print("Error:",e)
print("record inserted..")
Python | CCIT
print("record inserted..")
conn.commit()
conn.close()
except Exception as e:
print("Error:",e)
print("record inserted..")
conn.commit()
Python | CCIT
WAP to read accno and amt. Perform deposit operation on accmaster table
conn.commit()
Python | CCIT
WAP to read accno and display record of that account from accmaster table.
14
Python | CCIT
15
Python | CCIT
WAP to read accno and amount and perform withdraw operation on account.
(check if balance is available or not).
conn.close()
except Exception as e:
print("Error:",e)
WAP to read job and find list of empnames from emp table for that job
import mysql.connector as sql
try:
jb=input("Enter Job:")
conn=sql.connect(database="cmpdb",user="root",password=
"admin")
cmd="select name from emp where job= %s"
cur=conn.cursor()
cur.execute(cmd ,[ jb ])
rows=cur.fetchall()
for row in rows:
print(row[0])
conn.close()
except Exception as e:
print("Error:",e) 17
Python | CCIT
WAP to read empno and amt. Increment salary of that emp by specified amt
WAP to read name, job, salary and deptno. Insert a record into emp table.
conn.commit()
conn.close()
except Exception as e:
print("Error:",e)
20