How MySQL communicateswith Python
Python
Application Database
Executing SQL
statements
Retrieving query results
Communicates through DB API
3.
What is DBAPI?
The DB API provides a minimal standard for working with
databases structures and syntax from programming Language
such as Python, java wherever possible. This API includes the
following:
• Importing the API module.
• Acquiring a connection with the database.
• Issuing SQL statements and stored procedures.
• Closing the connection
You must download a separate DB API module for each database
you need to access. For example, if you need to access an Oracle
database as well as a MySQL database, you must download both
the Oracle and the MySQL database modules.
4.
Python DB-API
The Pythonstandard for database interfaces is the Python DB-API.
Most Python database interfaces adhere to this standard. We can choose the right
database for our application.
Python Database API supports a wide range of database servers such as : MySQL,
Microsoft SQL Server, Oracle, mSQL, PostgreSQL and many more.
Python DB-API is consists of Connection and Cursor data objects
• Connection data object – Various methods to establish connection and access
database.
• Cursor data object – Manipulates and retrieves data.
5.
What is MySQLdb?
MySQLdbis an interface for connecting to a MySQL database server from Python.
It is a third-party driver that provides MySQL support for Python, compliant with the
Python DB API version 2.0.
The new MySQL Connector/Python component provides an interface to the same
Python API, and is built into the MySQL Server and supported by Oracle.
A User can execute DDL, DML, DCL and TCL commands in MySQL through
python.
How do I Install MySQLdb?
pip install mysql-connector-python
And now import MySQLdb in python program or type- import MySQLdb
on interactive mode. If there is no error, it means driver is installed
successfully.
6.
Step for DatabaseConnectivity
Import MySQL Library
• Establish connection between MySQL & Python Application
• Execute SQL Statements from Python.
• Commit Changes to database.
• Close connection.
• Error handling if any that may occur during this process.
7.
Connection object
Connection ObjectsDescription
close() Closes the connection to the database.
commit() Commits (saves) a transaction (i.e., interaction with a
database through SQL keywords and commands).
rollback() Exits a pending transaction without saving changes.
Returns the user to the beginning of the transaction.
cursor() Returns a new Cursor object or the current connection
To create a connection between the MySQL database and the python
application, the connect() method of mysql. connector module is used. Pass the
database details like HostName, username, and the database password in the
method call. The method returns the connection object.
8.
Establishing connection
import mysql.connectoras sqlcnt
mycon=sqlcnt.connect(host="localhost", user="root", passwd="sia@1928",
database="oracledb")
print (mycon) # Statement to print status of connection
If you get below output, it mean connection with MySQL database named ‘oracledb’
is established successfully.
================RESTART: F:PythonPrgdb_demo.py =================
<mysql.connector.connection.MySQLConnection object at 0x0321DAD0>
Location
of
MySQL
Username
of MySQL
Password
of
MySQL
Name of
MySQL
Database. #the connect() constructor creates a connection to the MySQL
server and returns a mycon object
9.
Cursor object
Cursor ObjectsDescription
rowcount Returns the number of rows retrieved by the last execute method call.
close() Closes the cursor object.
Execute
(sql, [parameters])
Executes a SQL statement. The SQL statement may be parametrized (i.
e. placeholders instead of SQL literals).
executemany (sql,
seq_of_parameters)
Executes a SQL command against all parameter sequences or
mappings found in the sequence sql.
Executescript
(sql_script)
This is a nonstandard convenience method for executing multiple SQL
statements at once. It issues a COMMIT statement first, then executes
the SQL script it gets as a parameter.
fetchone(),fetchall(), fetchmany() are also methods of Cursor object.
Cursors are created through the connection by cursor() method: they are bound to
the connection for the entire lifetime and all the SQL commands are executed in
the context of the database session wrapped by the connection.
10.
Creating cursor object
Weneed to create the object of a class called cursor that allows Python code
to execute database command in a database session.
Cursors are created by the connection.cursor( ) method: they are bound to the
connection for the entire lifetime and all the commands are executed in the
context of the database session wrapped by the connection.
cursor=mycon.cursor()
11.
Fetch data fromdatabase
To fetch data from any database means to retrieve information from
the database. MySQLdb provides multiple ways to retrieve data such
as:
fetchall(): Fetch all (remaining) rows of a query result, returning them
as a sequence of sequences (e.g. a list of tuples).
fetchmany(size): Fetch the next set of rows of a query result, returning
a sequence of sequences (e.g. a list of tuples) .It will return number of
rows that matches to the size argument.
fetchone(): Fetch the next row of a query result set, returning a single
sequence, or None when no more data is available.
These methods generally used with Select query to retrieve data from
12.
Step for DatabaseConnectivity with Python
import mysql.connector as sqlcnt
mycon=sqlcnt.connect(host="localhost",user="root",passwd="123456
78",database="oracledb")
cursor=mycon.cursor()
mycon.commit()
cursor.close()
mycon.close()
• Catch Exception if any that may occur during this process.
sqlcmd="""insert into username values(%s,%s,%s)"""
cursor.execute(sqlcmd,record)
13.
Execute Insert query(Input from User)
Executes an SQL command against all parameter sequences or
mappings found in the sequence sql •
uname=input("Enter username=")
passw=input("Password=")
status=input ("Status- (Y/N)")
record=(uname,passw,status)
sqlcmd="""insert into username values(%s,%s,%s)"""
cursor.execute(sqlcmd, record)
mycon.commit()
It is always best practice to use parameterized query i.e. placeholders ( %s ) inside a
SQL statements that contain input from users. It is also required to use one
placeholder for every value passed to SQL Statement.
Placeholders
(one placeholder
for each value )
record is a collection holding values
received as input from user.
14.
Example Code-1 (Insertinga record)
import mysql.connector as sqlcnt
mycon=sqlcnt.connect(host="localhost",user="root",passwd="12345678",data
base="oracledb")
uname=input("Enter username=")
passw=input("Password=")
status=input ("Status- (Y/N)")
record=(uname,passw,status)
if mycon.is_connected():
print("Connection to Database Successful:")
cursor=mycon.cursor()
sqlcmd="""insert into username values(%s,%s,%s)"""
cursor.execute(sqlcmd,record)
mycon.commit()
cursor.close()
mycon.close()
else:
print("Unable to setup Connection to Database Successful:")
15.
Execute SQL query(Select)
We can execute the sql queries from python program using execute() method
associated with cursor object .
Examples –
"select * from employee where income > '%d'" % (1000)
cursor.execute("select * from username")
sqlQuery="""select * from username where userid = %s and status =%s""“
cursor.execute(sqlQuery, (uname, sts ))
QueryArgs = (uname,sts)
sqlQuery="""select * from username where userid = %s and status =%s""“
cursor.execute(sqlQuery,QueryArgs)
16.
Example Code-2 (ToFetch Data)
import mysql.connector as sqlcnt
mycon=sqlcnt.connect(host="localhost",user="root",passwd=“12345678",database="oracledb")
uname=input("Enter Username:")
sts=input("Enter status")
record = (uname,sts)
try:
if mycon.is_connected():
print("Connection to Database Successful:")
cursor=mycon.cursor()
sqlQuery="""select * from username where userid = %s and status=%s"""
cursor.execute(sqlQuery,record)
resultset=cursor.fetchone()
count=cursor.rowcount
print("Total Records",count)
for row in resultset:
print(row)
else:
print("Unable to setup Connection to Database Successful:")
except mysql.connector.Error as error:
print("Failed to get record from database: {}".format(error))
finally:
# closing database connection.
if (mycon.is_connected()):
cursor.close()
mycon.close()
print("connection is closed")
Error Handling or
Exception handling in
python is done by try,
except and finally
statements.
An exception is an
event, which occurs
during the execution of
a program, that
disrupts the normal
flow of the program's
instructions..
17.
Execute SQL query(update)
Executes an SQL command against all parameter sequences or mappings
found in the sequence sql .
record=( ‘N’ ,’Siya’)
sqlcmd="update username set status=%s where userid=%s"
cursor.execute(sqlcmd,record)
mycon.commit()
18.
Example Code-3 (ToModify Record (s))
import mysql.connector as sqlcnt
mycon=sqlcnt.connect(host="localhost",user="root",passwd=“sia@1928",database="oracled
b")
uname=input("Enter username=")
status=input ("Status- (Y/N)")
record=(uname,status)
if mycon.is_connected():
print("Connection to Database Successful:")
cursor=mycon.cursor()
sqlcmd="update username set status=%s where userid=%s"
cursor.execute(sqlcmd,record)
mycon.commit()
cursor.close()
mycon.close()
else:
print("Unable to setup Connection to Database Successful:")
19.
Execute SQL query(Delete)
Executes an SQL command against all parameter sequences or mappings
found in the sequence sql •
record=( ‘N’ ,’Siya’)
sqlcmd=“delete from username where status=%s and userid=%s"
cursor.execute(sqlcmd,record)
mycon.commit()
20.
Example Code-4 (ToDelete Record (s))
import mysql.connector as sqlcnt
mycon=sqlcnt.connect(host="localhost",user="root",passwd="12345678",database="oracled
b")
uname=input("Enter username=")
status=input ("Status- (Y/N)")
record=(uname,status)
if mycon.is_connected():
print("Connection to Database Successful:")
cursor=mycon.cursor()
sqlcmd=“delete from username where status=%s and userid=%s"
cursor.execute(sqlcmd,record)
mycon.commit()
cursor.close()
mycon.close()
else:
print("Unable to setup Connection to Database Successful:")