Interface python with an SQL database
Database connectivity: - Database connectivity refers to connection and
communication between an application and a
database system.
• Mysql.connector:- Library or package to connect from python to
MySQL.
• Command to install connectivity package: - pip install mysql-connector-
python
• Command to import connector: - import mysql.connector
• Steps for python MySQL connectivity:-
1. Install Python
2. Install MySQL
3. Open Command prompt
4. Switch on internet connection
5. Type pip install mysql-connector-python and execute
6. Open python IDLE
7. import mysql.connector
Steps for Creating Database Connectivity Applications :-
There are mainly seven steps that must be followed in order to create a
database connectivity application.
Step 1 :- Start Python.
Step 2 :- Import the packages required for database programming.
Step 3 :- Open a connection to database.
Step 4 :- Create a cursor instance.
Step 5 :- Execute a query.
Step 6 :- Extract data from result set.
Step 7 :- Clean up the environment.
2. Import mysql.connector Package :-
import mysql.connector
import mysql.connector as sqlcon
3. Open a Connection to MySQL Database :-
The connect() function of mysql.connector establishes connection to a
MySQL database and requires four parameters, which are ;
<Connection-Object>= mysql.connector.connect (host = <host-
name>, user = <username>,
passwd = <password> [, database = <database>])
user is the username on MySQL
password is the password of the user
host-name the database server hostname or IP address
database is optional which provides the database name of a MySQL
database.
Checking connection :-
import mysql.connector as sqltor
mycon = sqltor.connect(host="localhost", user = "root", passwd =
"MyPass", database="test")
if mycon.is_connected():
print('Successfully Connected to MySQL database')
4. Create a Cursor Instance :-
A Database Cursor is a special control structure that facilitates the row by
row processing of records in the resultset, i.e., the set of records retrieved as
per query.
<cursorobject>=<connectionobject>.cursor()
cursor = mycon.cursor()
5. Execute SQL Query :-
<cursorobject>.execute(<sql query string>)
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 programs/scripts as required.
6. Extract Data from Resultset :-
RESULT SET
The result set refers to a logical set of records that are fetched from the
database by executing an SQL query and made available to the application
program.
(i) <data> = <cursor>.fetchall(). It will return all the records retrieved as per
query in a tuple form (i.e., now <data> will be a tuple.)
(ii) <data> = <cursor>.fetchone(). It will return one record from the resultset as
a tuple or a list. First time it will return the first record, next time it will fetch the
next record and so on.
This method returns one record as a tuple: if there are no more records then it
returns None
(iii) <data> = <cursor>.fetchmany(<n>). This method accepts number of
records to fetch and returns a tuple where each record itself is a tuple. If there
are not more records then it returns an empty tuple.
(iv) <variable> = <coursor.rowcount. The rowcount is a property of cursor
object that returns the number of rows retrieved from the cursor so far.
7. Clean Up the Environment :-
After you are through all the processing, in this final step, you need to close
the connection established.
<connection
object>.close()
mycon.close()
commit – MySQLConnection.commit() method sends a COMMIT statement
to the MySQL server, committing the current transaction.
Functions to execute SQL queries:-
1. CREATE DATABASE
import mysql.connector as my
mydb = my.connect(host = "localhost", user = "root", password =
"123456")
mycon = mydb.cursor()
mycon.execute("CREATE DATABASE XYZ")
2. SHOW DATABASE
import mysql.connector as my
mydb = my.connect(host = "localhost", user = "root", password =
"123456")
mycon = mydb.cursor()
mycon.execute("SHOW DATABSES")
for i in mycon:
print (i)
3. CREATE TABLE
import mysql.connector as my
mydb = my.connect(host = "localhost", user = "root", password =
"123456", database = "XYZ")
mycon = mydb.cursor()
mycon.execute("CREATE TABLE student (Name char (25), roll
int(10), class int(10))")
mydb.commit()
mydb.close()
4. SHOW TABLE
import mysql.connector as my
mydb = my.connect(host = "localhost", user = "root", password =
"123456", database = "XYZ")
mycon = mydb.cursor()
mycon.execute("SHOW TABLES")
for i in mycon:
print (i)
5. DESCRIBE TABLE
import mysql.connector as my
mydb = my.connect(host = "localhost", user = "root", password =
"123456", database = "XYZ")
mycon = mydb.cursor()
mycon.execute("DESC student")
data = mycon.fetchall()
for i in data:
print (i)
6. SELECT QUERY
import mysql.connector as my
mydb = my.connect(host = "localhost", user = "root", password =
"123456", database = "XYZ")
mycon = mydb.cursor()
mycon.execute("SELECT * FROM student")
data = mycon.fetchall()
for i in data:
print (i)
7. WHERE CLAUSE
import mysql.connector as my
mydb = my.connect(host = "localhost", user = "root", password =
"123456", database = "XYZ")
mycon = mydb.cursor()
mycon.execute("SELECT * FROM student where Class = 12")
data = mycon.fetchall()
for i in data:
print (i)
8. DYNAMIC INSERTION
Forming Query Strings :-
Old Style: String Templates with % formatting
"select * from student where marks > %s"
New Style: String Templates with % formatting
import mysql.connector as my
mydb = my.connect(host = "localhost", user = "root", password =
"123456", database = "XYZ")
mycon = mydb.cursor()
name = input("Enter Name :-")
roll = input("Enter Roll :-")
class =input("Enter Class :-")
mycon.execute("INSERT INTO student VALUES ('{}', '{}',
'{}',)".format (name, roll, class))
mydb.commit()
mydb.close()
9. UPDATE COMMAND
import mysql.connector as my
mydb = my.connect(host = "localhost", user = "root", password =
"123456", database = "XYZ")
mycon = mydb.cursor()
mycon.execute("UPDATE student SET roll = 5 WHERE Name = 'Ram'")
mydb.commit()
mydb.close()
10. DELETE COMMAND
import mysql.connector as my
mydb = my.connect(host = "localhost", user = "root", password =
"123456", database = "XYZ")
mycon = mydb.cursor()
mycon.execute("DELETE FROM student WHERE roll = 26")
mydb.commit()
mydb.close()