Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
12 views

Interface Python With MySQL-1

Uploaded by

anilkoranga.pc
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Interface Python With MySQL-1

Uploaded by

anilkoranga.pc
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Interface Python with MySQL

For designing a real life project, you need to store the data either in form of files or in
database. As DBMS gives more options and flexibility to work on data, so it is preferred
over normal data files. The Python standard for database interfaces is the Python DB-
API. Most Python database interfaces adhere to this standard.
You can choose the right database for your application. Python Database API supports a
wide range of database servers. We will be using MySQL Connector Library to connect
to database.

 Python must be installed on your machine.


Note: – MySQL Connector Python requires python to be in the system’s PATH.
Installation fails if it doesn’t find Python.

 On Unix and Unix-like systems, Python generally located in a directory included in the
default PATH setting.

 On Windows, If Python doesn’t exist in the system’s PATH, please manually add the
directory containing python.exe yourself.
Right click on My Computer icon, click on Properties, then Advanced system settings
and Environment variables. Without deleting anything add <pythonpath>. If you have
Python.exe file in path in “C:\Python37-64\python.exe” then add the same to path
variable.
There are multiple ways to install Oracle’s MySQL Connector Python on your machine. The
following are a few ways.

 Install MySQL Connector Python using the pip command


 Install MySQL connector python via source code (via ZIP or TAR file)
 Use Built Distribution A package created in the native packaging format intended for
a given platform. Example, RPM packages for Linux or MSI installer for windows.

Pip Command to install MySQL Connector python


It is always accessible and straightforward to install any module using pip (Python Package
Installer) in python. MySQL Connector Python is available on pypi.org so you can install
using pip command in command prompt.
Using pip command, you can install MySQL Connector python on any operating system
platform including Windows, macOS, Linux, and Unix and Ubuntu.
Open command prompt/ Python Package Manager, then use pip command:
For Python 2.7 or lower install using pip as:.
pip install mysql-connector-python

For Python 3 or higher version install using pip3 as:

pip3 install mysql-connector


On Anaconda Python open Anaconda Prompt an install as:
conda install –c anaconda mysql-connector-python

You should get the following messages after running pip command: –

Collecting mysql-connector-python…….

Downloading packages……….

Requirement already satisfied: setup tools in D:python\python37-32\lib\site-packages.

Installing collected packages: mysql-connector-python

Successfully installed mysql-connector-python-8.0.13

Steps To Follow In Python To Work With MySQL


1. Connect to the database.
2. Create an object for your database.
3. Create a cursor instance
4. Execute the SQL query.
5. Fetch records from the resultset.
6. Informing the Database if you make any changes in the table.
Connect to database
Before Connecting to database first open Python’s Editor where you can create your Python
Script. Now you need to import mysql.connector Package to your program:
import mysql.connector
Now we will open a connection to MySQL Database:
To establish connection with MySQL database use connect () method of mysql.connector
package, which requires four parameters:
Syntax to access MySQL with Python:
import mysql.connector
<connection_object> = mysql.connector.connect(
host="hostname",
user="username",
passwd="password" )
Arguments required to connect MySQL from Python
You need to know the following detail of the MySQL server to perform the connection from
Python.
 Username – i.e., the username that you use to work with MySQL Server. The default
username for the MySQL database is “root”
 Password – Password is given by the user at the time of installing the MySQL
database. If you are using root then you won’t need the password.
 Host Name – is the server name or Ip address on which MySQL is running. if you are
running on localhost, then you can use localhost, or it’s IP, i.e. 127.0.0.0
 Database Name – Database name to which you want to connect.
Test the MySQL Database connection with Python
To test database connection here we use pre-installed MySQL connector and pass
credentials into connect() function like host, username and password.

Example,

import mysql.connector #import the package


db_connection = mysql.connector.connect(
host="localhost",
user="root",
passwd="")
print(db_connection)# Connection Object

Output:

<mysql.connector.connection.MySQLConnection object at 0x000002338A4C6B00>

Here output shows the connection created successfully.

Create Cursor Instance

The MySQLCursor of mysql-connector-python (and similar libraries) is used to execute


statements to communicate with the MySQL database. Once we connect to a database
from Python program, and query is sent to server, where it gets executed, and a resultset
(set of records retrieved) is sent back to connection in one go (all records together).Using
the methods of cursor object you can execute SQL statements, fetch data from the result
sets, call procedures.

You can create Cursor object using the cursor() method of the Connection object/class.
Syntax:
<cursor_object>= connection_object.cursor()
#Creating a cursor object using the cursor() method
cursor = db_connection.cursor()

Execute SQL Query


After establishing link with database and creating cursor object you can execute any SQL
query using execute() function with cursor object with following syntax:

<cursorobject>.execute(<SQL query as string>)


Now to create a database named school, query may be written as
cursor.execute(“create database school”)
The above query will create a new database named school in MySQL.
To view all the databases query can be written:
cursor.execute(“show databases”)
The above code will execute the query and store the resultset (names of all the databases)
in the cursor object (i.e. cursor, in this case), which can now be used in program as
required.

Extract Data From Resultset


To extract the data stored in the reultset we can use the methods and properties defined
with the cursor object.

Following are the various methods provided by the Cursor class/object.


Sr.No Method & Description
1 callproc()
This method is used to call existing procedures of MySQL database.
2 close()
This method is used to close the current cursor object.
3 Info()
This method gives information about the last query.
4 executemany()
This method accepts a list series of parameters list. Prepares an MySQL query and executes it
with all the parameters.
5 execute()
This method accepts a MySQL query as a parameter and executes the given query.
6 fetchall()
This method retrieves all the rows in the result set of a query and returns them as list of tuples.
(If we execute this after retrieving few rows it returns the remaining ones)
7 fetchone()
This method fetches the next row in the result of a query and returns it as a tuple.
8 fetchmany( n )
This method is similar to the fetchone() but, it retrieves the next (n) set of rows, passed as
argument (n), in the result set of a query, instead of a single row.
9 fetchwarnings()
This method returns the warnings generated by the last executed query.

Properties
Following are the properties of the Cursor class –
Sr.No Property & Description
1 column_names
This is a read only property which returns the list containing the column names of a result-set.
2 description
This is a read only property which returns the list containing the description of columns in a
result-set.
3 lastrowid
This is a read only property, if there are any auto-incremented columns in the table, this returns
the value generated for that column in the last INSERT or, UPDATE operation.
4 rowcount
This returns the number of rows returned/updated in case of SELECT and UPDATE
operations.
5 statement
This property returns the last executed statement.
Now let’s write a complete script to create connection object and cursor object, put and
execute queries to create a database and list all the databases available by extracting data
from the resultset.

import mysql.connector as msc #alias name for connector


#creating connection object as mydb
mydb=msc.connect(host="localhost",user="root",passwd="netcom")
print(mydb)# to check connection
#creating cursor object as mycursor
mycursor=mydb.cursor()
mycursor.execute("CREATE DATABASE SCHOOL")#Create a Database
mycursor.execute("SHOW databases")# SHOW DATABASE
#Extracting resultset from mycursor
for x in mycursor:
print (x)#Will display names of all databases
to use (open) a database either it can be mentioned as argument while creating
connection object:
mydb=msc.connect(host="localhost",user="root",passwd="netcom",
database=”school”) # will open the database with connection

or query can be made


mydb=msc.connect(host="localhost",user="root",passwd="netcom")
mycursor=mydb.cursor()
mycursor.execute("use school")# will open the database

You might also like