CH 16 Interface Python With Mysql
CH 16 Interface Python With Mysql
In order to connect to a database from within Python, you need a library(mysql connector) that provides
connectivity functionality.
There are mainly seven steps that must be followed in order to create a database connectivity
application.
First of all we need to import mysql.connector package in your Python scripts. For this, write import
command as shown below:
import mysql.connector
or
import mysql.connector as sqLtor
The connect( ) function of mysql.connector establishes connection to a MySQL database and requires
four parameters, which are,
Syntax:
<Connection Object> = mysql.connector.connect(host = <hostname>, user = <username>, passwd =
<password>, database = <database>)
Example:
When we connect to a database from within a script/program, then the query gets sent to the server,
where it gets executed, and the resultset (the set of records retrieved as per query) is sent over the
connection to you, in one burst of activity, i.e. in one go. And in order to do the processing of data row
by row, a special control structure is used, which is called Database Cursor.
Syntax:
<CursorObject> = <Connection Object>.cursor();
Eg :
Cursor = Mycon.cursor();
Execute a query
Once you have created a cursor, you can execute SQL query using execute( ) function with cursor object
as per following
Syntax :
<SursorObject>.execute(<Query String>)
Eg :
cursor.execute(“Select * from Employee”)
The above code will execute the given SQL query and store the retrieved records(i.e. , the resultset) in
the cursor object (namely cursor) which you can then use in your program/scripts as required.
Once the result of query is available in the form of a resultset stored in a cursor object, you can extract
data from the resultset using any of the following fetch( ) functions.
(i) = <cursor>.fetchall( )
(ii) = <cursor>.fetchone( )
(iii) =<cursor>.fetchmany()
(iv) =<cursor>.rowcount
Performing INSERT and UPDATE Queries
Insert and Update SQL commands, can also executed using SELECT queries.
But after executing INSERT and UPDATE queries you must commit your query. This
makes the changes made by the INSERT and UPDATE queries permanent. For this you
must run commit( ) method ,
INSERT query example
st = “INSERT INTO student (rollno , name , marks , marks , grade, section) VALUES({ } , ‘{ }’ , { } , ‘{ }’, ‘{ }’
)”.format( 108,’Eka’ , 84.0 , ‘A’ , ‘B’)
cursor.execute(st)
mycon.commit( )
Important definition:
Database connectivity refers to connection and communication between an application and a database
system.
A Connection (represented through a connection object) is the session between the application
program and a database. To do anything with database, one must have a connection object.
A result set refers to a logical set of records that are fetched from the database by executing a query
and made available to the application-program.