DATABASE CONNECTIVITY
Python supports connection with MYSQL (and other databases) to manage data in Database through
Python Interface. Python’s mysql.connector module provides programming support for establishing
connection with a MYSQL Database, perform database operations and execute queries.
Steps for connecting to MYSQL from Python
1. Import the mysql.connector module
2. Create a Connection Object - Python allows programs to access MySQL databases through
mysql.connector module. It’s connect() method is used to establish a connection between
MySQL and Python Program/Interface. It returns a MySQLConnection object if the connection
is established successfully. connect() method takes four parameters – host set to localhost,
user & passwd for username & password which should be the as set during MySQL installation
and an optional database parameter which should be set to the database name or skipped
when there is a need to create a database
ConnectionObject = mysql.connector.connect(host = "localhost", user = "username",
passwd= “password”, database= “dbname”)
Note : - we may use an alias for mysql.connector as follows
import mysql.connector as sqlcon
Example
ConObj = sqlcon.connect(host=“localhost”, user=“root”, passwd=“root”, database=“ProdDB”)
if mycon:
print(mycon)
3. Create a Cursor Object
A cursor object is a control structure used for executing query and processing data from the
Result Set row-wise. The cursor() method of the connection object is used to create a cursor
object.
CursorObj=ConObj.cursor( )
4. Execute Query
The execute() method of the cursor object is used to execute the SQL statements in Python.
The query is passed as a string.
CursorObj.execute(“query”)
Whenever any change is made to data in a relation, the changes should be made permanent
using the commit( ) method of the connection object.
ConObj.commit( )
5. Fetch Results and display as required
Result of the query called the result set. Each record is returned as a python tuple and all
records in result set is returned as a list of tuples. Data may be fetched using the following
fetchone( ) – it fetches the first record / current record
fetchmany(N) – fetches N records from the beginning / current position
fetchall( ) – fetches all the records
rowcount – returns the number of records
6. Close the Connection
Link with the database may be terminated by closing the connection object. Closing a
connection is important for releasing the resources and clean up the environment.
ConObj.close()
1. CREATE A DATABASE
Output
Connection established successfully
Database created…
2. CREATING A TABLE
Output
Student table created…
3. INSERT RECORD
Output
Student Record inserted…
4. DISPLAY ALL RECORDS
Output
Records in the Result Set 2
[(10010, 'Amar'), (10011, 'Jyoti')]
Display individual records
(10010, 'Amar')
(10011, 'Jyoti')
5. UPDATE DATA
Output
Updated data...
(10010, 'Amarjit')
(10011, 'Jyoti')
6. DELETING A RECORD
Output
Data after deleting the record...
(10011, 'Jyoti')