Interface python with
MySQL Database
Why choose Python for database
programming
Following are the reason to choose python for database programming
Programming more efficient and faster compared to other languages.
Portability of python programs.
Support platform independent program development.
Python supports SQL cursors.
Python itself take care of open and close of connections
Python supports relational database systems.
Sorting of data from one dbms to other is easily possible as it support large range of
APIs for various databases.
CLIENT AND SERVER CONNECTION:-
PYTHON AND DB CONNECTION
SQL Connectors
The DB API provides a minimal standard for working with
databases using Python structures and syntax 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
STEP 1:- import the module
Import [Link]
Or
Import [Link] as sqltor
Step 2:- Establish connection
For database interface/database programming ,connection must be
established. Before establishing connection there must be mysql
installed on the system and a database and table is already created:-
mydb=[Link](host="localhost",user="root"
,passwd="root“,database=“school”)
we are specifying host,user,password and database name as arguments.
Database is optional argument if we want to create database through
programming later on
Step 3:- Cursor object
MySQLCursor class instantiates objects that can execute
operations such as SQL statements. Cursor objects interact
with the MySQL server using a MySQLConnection object.
mycursor=[Link]()
Step 4:- Execute Queries
Execute function of the cursor object executes the query
on the server. We can run DDL, DML etc all types of
queries.
[Link]("create database if not exists school")
Or
[Link](Query)
STEP 5:- Close the connection
Invoke the close function to close the connection and save
the results.
[Link]()
SELECTION of Data:-
When we run SELECT query, it results Resultset Object which contains
data returned from query. Following functions may be called to
retrieve he data from it.
Fetchone()
Fetchall()
Fetchmany()
Rowcount: returns number of row returned. (var)