MySql Interface
MySql Interface
SQL Database
Steps for creating Database connectivity applications :
Steps :
1. Start Python
2. Import the Packages required for database programming
3. Open a connection to database
4. Crate a cursor instance
5. Execute a query
6. Extract data from result set
7. Clean up the environment
2. Import the Packages:
import mysql.connector
or
import mysql.connector as sqlcon
It will imports the MySQL connector module/ package in Python script
in our program.
Open a connection to MySQL
Database
The connect() function of mysql.connector used to establish connection
to a MySQL database end returns a MySQLConnection object. It
requires four parameters host, user, passwd and databse.
<connectionobject> = mysql.connector.connect ( host=<hostname>,
user=<username>, passwd=<password>
[, databse=<database>])
Where host - the database server name;
default – “localhost”
username - the username on MySQL;
default –“root”
passwd – password of the user given at the time of installing MySQL database;
databse – optional; name of the database to which connectivity is to be established.
It will return one record from the resultset as a tuple. If there is no more
records then it return None. First time it will return the first record, next
time it will fetch the next record and so on.
It will return only the n number of rows from the resultset in the form
of tuple. If there are not more records then it returns an empty tuple.
(iv) <data>= <cursorobject>.
• rows = cursor.fetchmany(n)
• This method fetches the next set of rows of a query result and returns
a list of tuples. If no more rows are available, it returns an empty list
rowcount
Rows affected by Query. We can get number of rows affected by the query by
using rowcount. We will use one SELECT query here.
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="root",d
atabase="school")
mycursor=mydb.cursor()
mycursor = mydb.cursor(buffered=True)
mycursor.execute("select * from student")
noofrows=mycursor.rowcount
print("No of rows in student table are",noofrows)
buffered=True
We have used my_cursor as buffered cursor.
my_cursor = my_connect.cursor(buffered=True)
This type cursor fetches rows and buffers them after getting output
from MySQL database. We can use such cursor as iterator. There is no
point in using buffered cursor for single fetching of rows.If we don’t use
buffered cursor then we will get -1 as output from rowcount
7. Clean Up the Environment
After all processing, the connection must be closed.
<connectionobject>.close()