Interface Python with MySQL Notes (2)
Interface Python with MySQL Notes (2)
Basically the process of transfer data between python programs and MySQL database
is known as Python Database Connectivity.
There few steps you have to follow to perform Python Database Connectivity. These
steps are as follow:
2. Establish a connection
After installation just write the import statement to import the package in python
code.
Here I have instantiated msql to mysql.connector which can be work as an alias name
for the connector.
Establish a connection
cn=msql.connect(host='localhost',user='root',passwd='root',database='Studentdb')
Please ensure that you have provided appropriate username, password and database
name available in your MySQL interface.
After doing this, check for the errors if any. If your program runs without errors that
means connection is established. Although you can use is_connected() function to
check whether the connection is established or not! Observe this code:
cn=msql.connect(host='localhost',user='root',passwd='root',database='Student')
if cn.is_connected():
print("Connection Established")
else:
The next step after the successful connection is to write SQL command and fetch rows.
The SQL commands are used to perform DML operations and fetch rows read data
from table. So we will see them in detail later.
You have to create a cursor object for executing SQL command and fetch rows. Cursor
object is a special kind of structure that processes the data row by row in database.
You can create cursor object in the following manner.
cur=cn.cursor()
Performing DML operations (insert, update and delete)
To perform the DML operations like insert, update or delete follow these steps:
3. Use commit() function to save the changes and reflect the data in the table.
insert command
cn=msql.connect(host='localhost',user='root',passwd='1234',database='Studentdb')
cur=cn.cursor()
#or
b = input("Enter name")
c = eval(input("Enter Marks"))
d = input("Enter Grade")
#or
cur.execute("insert into students values({0},'{1}',{2},'{3}')".format(a,b,c,d))
cn.commit()
update command
cn=msql.connect(host='localhost',user='root',passwd='1234',database='Studentdb')
cur=cn.cursor()
c = eval(input("Enter Marks"))
#or
cn.commit()
delete command
cn=msql.connect(host='localhost',user='root',passwd='1234',database='Studentdb')
cur=cn.cursor()
#or
cur.execute("delete from students where rno={0}".format(a))
cn.commit()
Select Command
As you know the select command is used retrieve records from the database. The
result is available in the resultset or dataset. You can store the select the command in
cursor object in python. Then for resultset you can use the fetch…() function. These
are:
1. fetchall(): It will retrieve all data from a database table in form of record or tuple or
a row.
2. fetchone(): It will retrieve one record from the resultset as a tuple or a list. It returns
the records in a specific order like first record, the next time next record and so on. If
records are not available then it will return None.
3. fetchmany(n): It will retrieve a number of records from the database. If records are
not available then it will return an empty tuple.
4. rowcount: It is one of the properties of cursor object that return number of rows
fetched from the cursor object.
cn=msql.connect(host='localhost',user='root',passwd='1234',database='Studentdb')
cur=cn.cursor()
d=cursor.fetchall()
for r in d:
print(r)
cn=msql.connect(host='localhost',user='root',passwd='1234',database='Studentdb')
cur=cn.cursor()
d=cursor.fetchmany(3)
for r in d:
print(r)
import time
cn=msql.connect(host='localhost',user='root',passwd='1234',database='Studentdb')
cur=cn.cursor()
d=cur.fetchone()
print(d)
time.sleep(3)
d=cur.fetchone()
print(d)
time.sleep(3)
d=cur.fetchone()
time.sleep(3)
print(d)
Parameterized Queries
Sometimes we need to access values as per the user’s input. The query result is based
on the values user has passed. So for that we have this option parameterized queries.
There are two ways to use parameterized queries:
This pattern takes the general form – f % v, where f is a format and v is the value.
Consider the following
code:
import time
cn=msql.connect(host='localhost',user='root',passwd='1234',database='Studentdb')
cur=cn.cursor()
d=cur.fetchall()
for r in d:
print(r)
d=cur.fetchall()
for r in d:
print(r)
In this pattern you can write {} where the value is placed followed by .format(values).
Consider the following code:
import time
cn=msql.connect(host='localhost',user='root',passwd='1234',database='Studentdb')
cur=cn.cursor()
d=cur.fetchall()
for r in d:
print(r)
d=cur.fetchall()
for r in d:
print(r)
Finally, you have to close the established connect using close() function. It will help to
clean up the memory. Observe the following code:
con.close()