Interface Python With MYSQL
Interface Python With MYSQL
• The python programming language has powerful features for database programming.
• Python supports various databases like MySQl,Oracle,Sybase,Postgre(SQL),etc.
• Python also supports DDL and DML statements.
• Python DB-API(database application programming interface) is a widely used module that
provides a database application programming interface.
• Python database API supports a wide range of database servers:-
✓ MYSQL
✓ PostgreSQL
✓ Oracle
✓ Sybase
✓ Microsoft SQL Server 2000
ESTABLISHING CONNECTION:-
The next step is to make the connection with the database we wish to use.
Module_name.connect()
The connect() statement creates a connection to the MYSQL server and returns a mysql connection
object.
The second statement creates a connection object ‘mydb’ through localhost for mysql with
username as ‘root’ and password as blank in the above case.
a. Username:-this is the username that we use to work with MySQL server,The default is
“root”.
b. Password-If we are using root then we don’t need to specify password.
c. Hostname:-This is the server name or IP address on which MYSQL is running.
d. Database name
All are optional keyword arguments for connect() method.
The next step after creating connection using connect() is to create cursor object.The cursor object
let us execute all the queries we need.It gives us the ability to have multiple separate working
environments through the same connection to the database.
CREATING A DATABASE:-
ALL STEPS IN A GLANCE:-
1. import mysql.connector
In case the connection has failed or any other database error occurred while working on it
write:-
from mysql.connector import Error
2. mysql.connector.connect(host,database,user,passwd)
3. conn.is_connected()
It is one of the function of MYSQL coonection class through which we can check out python
application is connected to MySQL application or not.
4. cursor():-This method returns a cursor object which is used to execute SQL statements.
5. cursor().execute()
After writing the commit() the changes will be seen in the database
a. commit():-this method sends a commit statement to the MySQL server committing the
current transaction.
Syntax:-
connection.commit()
b. rollback():-It reverts the changes made by the current transaction.
Syntax:-
connection.rollback()
c. autocommit:-It is used to enable or disable the auto commit feature of MYSQL.
Connection.autocommit value can be assigned as True or False.By default it is False.
As we are performing the READ operation on the database to fetch some information using select
command
Updating value and Counting the count of rows using the attribute rowcount:-
CLOSING CURSOR AND CONNECTION:-
cursor.close()
OR
mycursor.close()
OR
conn.close()