Interface Python With SQL

Download as pdf or txt
Download as pdf or txt
You are on page 1of 5

Interface python with SQL

Database: A database is an structured collection of data stored in tables where a table is organised in
the form of rows and columns. A data is stored in the cell created by the intersection of a row and a
column. All companies whether large or small use databases. So, it become necessary to develop
project/software using any programming language like python in such a manner which can interface
with such databases which support SQL. The interface is created by python called as the front end
while the database is created by MySQL known as the back end.

SQL allows to write queries that manipulates data in the database. To script SQL queries in the
python program, we need to connect python with MySQL.

There are two ways to connect MYSQL with python.

Method 1. mysql-connector
MySQL-Connector enables Python programs to access MySQL databases, using an API that is
compliant with the Python Database

Steps to use mysql-connector

1. Download Mysql and install it.


(click here to download)

2. Install Mysql-Python Connector


(Open command prompt and execute command) >pip install mysql-connector

3. Now connect Mysql server using python

4. Write python statement in python shell import mysql.connector If no error message is shown
means mysql connector is properly installed

Sample Initial code:

import mysql.connector as ms
con1=ms.connect(host="localhost",user="root",passwd="root“,database=“school”)
cur1=con1.cursor()
cur1.execute(<sql command>)

if sql command is insert/delete/update/create/alter/drop then


con1.commit()

Method 2. MySQLdb
MySQLdb is an interface for connecting to a MySQL database server from Python.

Steps to use mysqlclient

1. First Upgrade pip command through > python–m pip install–upgrade pip

2. Install mysqlclient through pip install mysqlclient

3. After successful installation check through import mysqldb

4. If it is installed no error will be displayed otherwise error message will be displayed

Sample Initial code:


import MySQLdb as md
con1=md.connect(host="localhost",user="root",passwd="root“,database=“school”)
cur1=con1.cursor()
cur1.execute(<sql command>)

if sql command is insert/delete/update/create/alter/drop then


con1.commit()

How to create a table structure with table name student with three attributes at run time

import mysql.connector as ms
con1=ms.connect(host="localhost",user="root",passwd="root",database="school")
cur1=con1.cursor()
cur1.execute("create table student(rollno int(3) primary key,name varchar(20),age int(2))")
con1.commit()

On successful execution of above program a table named student with three fields rollno, name, age
will be created in school database. We can check student table in mysql shell also, if required.

How to change table structure/(add,edit,remove colum of a table) at run time

To modify the structure of the table we just have to use alter table query.
Below program will add a column mark in the student table.

import mysql.connector as ms
con1=ms.connect(host="localhost",user="root",passwd ="root",database="school")
cur1=con1.cursor()
s="alter table student add (marks int(3))"
cur1.execute(s)
s="desc student"
cur1.execute(s)
for x in cur1:
print(x)
con1.commit()

Above program will add a column marks in the table student and will display the structure of the
table

How to insert record in a table at run time

import mysql.connector as ms
con1=ms.connect(host="localhost",user="root",passwd="root",database="school")
cur1=con1.cursor()
while ch!=-1:
ch=int(input("enter -1 to exit any other no to insert record into student table"))
rollno=int(input("Enter rollno"))
class1=int(input("Enter Class"))
name=input("Enter name")
marks=int(input("Enter marks"))
cur1.execute("insert into student
values('"+str(rollno)+"','"+name+"','"+str(class1)+"','"+str(marks)+"')")

or

s=”insert into student values (%s, %s, %s, %s)”


val=(rollno, class1, name, marks)
cur1.execute(s,val)

con1.commit()

How to search records of a table at run time

Below statement demonstrate the use of select query for searching specific record from a table.

import mysql.connector as ms
con1=ms.connect(host="localhost", user="root", passwd="root", database="school")
cur1=con1.cursor()
nm=input("enter name")
s="select * from student where name=%s"
val(nm,)
cur1.execute(s,val)
for x in cur1:
print (x)

Above statements will prompt a name from user, as user type the name , that name is searched into
the table student with the help of select query .result will be shown with the help of cur1 collection.

How to fetch all records of a table at run time

import mysql.connector as ms
con1=ms.connect(host="localhost",user="root",passwd="root",database="school")
cur1=con1.cursor()
cur1.execute("select * from student")
myrecords=cur1.fetchall()
for x in myrecords:
print (x)

MySQLCursor.fetchall() Method: The method fetches all (or all remaining) rows of a query result set
and returns a list of tuples. If no more rows are available, it returns an empty list.

How to fetch one record of a table at run time

import mysql.connector as ms
con1=mysql.connector.connect(host="localhost",user="root",passwd="root",database="school")
cur1=con1.cursor()
s="select * from student"
cur1.execute(s)
row=cur1.fetchone()
while row is not None:
print(row)
row =cur1.fetchone()
MySQLCursor.fetchone() Method: This method retrieves the next row of a query result set and
returns a single sequence, or None if no more rows are available. By default, the returned tuple
consists of data returned by the MySQL server, converted to Python objects.

MySQLCursor.fetchmany() Method: rows = cursor.fetchmany(size=1) This method fetches the next set
of rows of a query result and returns a list of tuples. If no more rows are available, it returns an
empty list.

rowcount : Rows affected by Query.

We can get number of rows affected by the query by using rowcount.

import mysql.connector as ms
con1=ms.connect(host="localhost",user="root",passwd="root",database="school")
cur1=con1.cursor()
s="select * from student"
cur1.execute(s)
n=cur1.rowcount
print("No of rows in student table are", n)

How to delete record of a table at run time

import mysql.connector as ms
con1=ms.connect(host="localhost",user="root",passwd="root",database="school")
cur1=con1.cursor()

s="delete from student where rollno=1"


cur1.execute(s)
con1.commit()

In above program delete query will delete a record with rollno=1. commit() method is necessary to
call for database transaction.

How to update record of a table at run time

import mysql.connector as ms
con1=ms.connect(host="localhost",user="root",passwd="root",database="school")
cur1=con1.cursor()
s="update student set marks=99 where rollno=2"
cur1.execute(s)
con1.commit()

In above program update query update the marks with 99 of rollno=2 Students are advised to
develop menu driven program using above concepts for better understating of python mysql
database interface.

Manage Database Transaction Database transaction represents a single unit of work.

Any operation which modifies the state of the MySQL database is a transaction. Python MySQL
Connector provides the following method to manage database transactions.

commit– MySQLConnection.commit() method sends a COMMIT statement to the MySQL server,


committing the current transaction.
rollback– MySQLConnection.rollback revert the changes made by the current transaction.
AutoCommit– MySQLConnection.autocommit value can be assigned as True or False to enable or
disable the auto-commit feature of MySQL. By default its value is False.

import mysql.connector as ms

try:
con1 = ms.connect(host='localhost', database='school', user='root', password='root')
con1.autocommit = false
cur1 = con1.cursor()
s = "update student set marks = 95 where rollno = 2"
cur1.execute(s)
print ("Record Updated successfully ")
con1.commit()

except ms.Error as error :


print("Failed to update record to database rollback: {}".format(error))
con1.rollback()
finally:
if(con1.is_connected()):
cur1.close()
con1.close()
print("connection is closed")

In above program if update query is successfully executed then commit() method will be executed
otherwise exception error part will be executed where revert of update query will be done due to
error. At finally we are closing cursor as well as connection. To rollback or commit we have to set
autocommit=false, just like con1.autocommit = false in above program otherwise rollback will not
work

You might also like