0% found this document useful (0 votes)
5 views17 pages

Python & MySQL

Uploaded by

ankitbomber01
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
5 views17 pages

Python & MySQL

Uploaded by

ankitbomber01
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 17

Python & MySQL

Interface Between Python and MySQL

1
MySQL-Connector-Python module in Python

MySQL is a Relational Database Management System (RDBMS) whereas the structured Query
Language (SQL) is the language used for handling the RDBMS using commands i.e Creating,
Inserting, Updating and Deleting the data from the databases. SQL commands are case
insensitive i.e CREATE and create signify the same command.
What is MYSQL Connector/Python?
MySQL Connector/Python enables Python programs to access MySQL databases

Installing module

This module does not come built-in with Python. To install it type the below command
in the command prompt.

pip install mysql-connector-python


2
Verifying MySQL Connector/Python installation

After installing the MySQL Python connector, we need to test it to make sure that it is
working correctly and we are able to connect to the MySQL database server without any
issues.
To verify the installation, we can use the following steps:
1. Open Python command line
2. Type the following code

>>>import mysql.connector
>>> mysql.connector.connect(host="localhost",user="root",passwd="amit“ , database=“abc”)

Output:
<mysql.connector.connection.MySQLConnection object at 0x02DD6CB0>
3
Connect MySQL database using MySQL-Connector Python

The connect ( ) function of mysql.connector establishes connection to a mysql database and


requires four parameters, which are

<connection-Object>=mysql.connector.connect(host=“host-name”, user=“user-name”,
passwd=“password” , database=“database-name”)

A database Connection object controls the connection to the database .It represent a unique
session with a database connected from within a script/program.

# Python program to connect to mysql dataabse


import mysql.connector as con
# Connecting from the server
db= con.connect(user = ‘root', host = 'localhost‘, passwd=‘ ‘ , database = 'databsename')
print(db)
db.close() # Disconnecting from the server
4
Connect MySQL database using MySQL-Connector Python

# Python program to check connection using is_connected( ) method.

import mysql.connector as con

db= con.connect(user = ‘root', host = 'localhost‘, passwd=‘ ‘ , database = ‘abc')

If db.is_connected( ):
print(“ Successfully connected with mysql database”)
db.close()

5
Python MySQL – Create cursor Instance

A database cursor is a useful control structure of database connectivity that


facilitates the row by row processing of records in the resultset , i.e, the set of
records retrieved as per query.
<cursorobject>=<connectionobject>.cursor( )
cur=db.cursor( )

6
Python MySQL – Execute SQL Query

7
Python MySQL – Create Database

# importing required libraries


import mysql.connector as con
db = con.connect(host ="localhost", user ="user", passwd =“amit”)

cur = db.cursor( ) # preparing a cursor object

cur.execute("CREATE DATABASE abc") # creating database

The above program illustrates the creation of MySQL database abc in which host-
name is localhost, the username is root and password is amit.

8
Python Mysql Connector Module Methods
1. connect() :
This Function is used for establishing connection with the MySQL server. The following are the
arguments that are used to initiate a connection.
• user: User name associated with the MySQL server used to authenticate the connection
• password: Password associated with the user name for authentication
• database: Database in the MySQL for creating the Table .

2. cursor()
Cursor is the work space created in the system memory when the SQL command is executed .
This memory is temporary and the cursor connection is bounded for the entire session/
lifetime and the commands are executed

3. execute()
The execute function takes a SQL query as an argument and executes . A query is any SQL
command which is used to create, insert, retrieve, update, delete etc.
9
Python: MySQL Create Table

import mysql.connector as con


db = con.connect(host ="localhost", user ="user", passwd =“amit” , database=“abc”)
cur = db.cursor( )
# creating table
cur.execute("CREATE table emp (eno int(5) , name varchar(20))")

db.close()

10
Python MySQL – Insert into Table

import mysql.connector as con


db = con.connect(host ="localhost", user ="user", passwd =“amit” , database=“abc”)
cur = db.cursor( )
cur.execute(“insert into emp values(101,’anuj’)")

db.commit( )

db.close()

Without the command db.commit() the changes will not be saved.

11
Python MySQL – Update Table

The update is used to change the existing values in a database. By using update a
specific value can be corrected or updated. It only affects the data and not the
structure of the table.

import mysql.connector as con


db = con.connect(host ="localhost", user ="user", passwd =“amit” , database=“abc”)
cur = db.cursor( )
cur.execute(“update emp set name =‘amit’ where eno=101")

db.commit( )
db.close()

Without the command db.commit() the changes will not be saved.


12
Python MySQL – Delete record

import mysql.connector as con


db = con.connect(host ="localhost", user ="user", passwd =“amit” , database=“abc”)
cur = db.cursor( )
cur.execute(“delete from emp where eno=101")

db.commit( )

db.close()

Without the command db.commit() the changes will not be saved.

13
Python Program to fetch record(s) from a Table

Select command in SQL is used to fetch record from any existing table(s). There are three types of
records this command can produce
1. Single word
2. Single record
3. Multiple record

Single Word Output :


1. Select name from student where admno=1234
2. select sum(fees) from student
Single record output:
1. select name, class, stream, fees from student where admno = 1234
2. select * from student where admno = 234
Multiple records output
1. select * from student
2. select admno, name, stream from student where stream =‘science’ or grade =‘A’
14
fetchone() method

fetchone() method is used with database cursor() to pick one row from the cursor and
return it as a tuple().
Syntax of fetchone() method
result = cursor.fetchone()

import mysql.connector as con


db = con.connect(host ="localhost", user ="user", passwd =“amit” , database=“abc”)
cur = db.cursor( )
cur.execute(“select name from emp where eno=101 ")
name = cur.fetchone( )
print(“employee name is : “, name)
db.close() 15
fetchone() method continued …

import mysql.connector as con


db = con.connect(host ="localhost", user ="user", passwd =“amit” , database=“abc”)
cur = db.cursor( )
cur.execute(“select eno,name from emp where eno=101 ")
rec = cur.fetchone( )
Printed whole Tuple
print(“employee record is : “,rec )
print(“employee eno is : “,rec[0] )
Printing individual value using index
print(“employee name is : “,rec[1] )

db.close()
16
Python MySQL – Select Query (fetchall method)

Python Program to retrieve multiple lines from a table

import mysql.connector as con


db = con.connect(host ="localhost", user ="user", passwd =“amit” , database=“abc”)
cur = db.cursor( )
cur.execute(“select * from emp")

rec= cur.fetchall( )

for i in rec:
print(i)

db.close()
17

You might also like