Advance Python Unit - 4
Advance Python Unit - 4
Interaction
nteraction with Database
Environment Setup
Python can be used in database applications.
applications.Python
Python Database API supports a wide range of
database servers. One of the most popular databases is MySQL.
For
or using MySQL with python you should have
MySQL
SQL installed on your computer.
At the time of installation you have to install server and mysql connector for Python.
After installing navigate your command line to the location of PIP, and type the following:
To test if the installation was successful, or if you already have "MySQL Connector" installed,
create a Python page with the following content:
test.py:
import mysql.connector
If the above code was executed with no errors, "MySQL Connector" is installed and ready to be
used.
Create Connection
Start by creating a connection to the database.
import mysql.connector
mydb = mysql.connector.connect(host="localhost",user="yourusername",password="yourpassword")
print(mydb)
connect():
The connect() constructor creates a connection to the MySQL server and returns a
MySQLConnection object. Then we can use MySQL connection object to perform various
operations on the MySQL database.
The connect() method accepts four parameters: host, database, user and password. Here user is
the name of user used to authenticate with the MySQL server. Password is the password to
authenticate the user with the MySQL server. Database is the database name use to use when
connecting with the MySQL server. Host name is the host name or IP address of the MySQL
server.
The connect() method can throw an exception, i.e. if database error if one of the required
parameter is wrong.
Creating a Database
To create a database in MySQL, use the "CREATE DATABASE" statement:
Example
create a database named "mydatabase":
import mysql.connector
mydb = mysql.connector.connect(host="localhost",user="yourusername",password="yourpassword")
mycursor = mydb.cursor()
cursor():
You can create cursor object using the cursor method of the connection object/class.
Methods
1
callproc()
This method is used to call existing procedures MySQL database.
2
close()
This method is used to close the current cursor object.
3
Info()
This method gives information about the last query.
4
executemany()
This method accepts a list series of parameters list. Prepares an MySQL query and executes it with all
the parameters.
5
execute()
This method accepts a MySQL query as a parameter and executes the given query.
6
fetchall()
This method retrieves all the rows in the result set of a query and returns them as list of tuples. (If we
execute this after retrieving few rows it returns the remaining ones)
7
fetchone()
This method fetches the next row in the result of a query and returns it as a tuple.
8
fetchmany()
This method is similar to the fetchone() but, it retrieves the next set of rows in the result set of a query,
instead of a single row.
9
etchwarnings()
This method returns the warnings generated by the last executed query.
Properties
1
column_names
This is a read only property which returns the list containing the column names of a result-set.
2
description
This is a read only property which returns the list containing the description of columns in a result-set.
3
lastrowid
This is a read only property, if there are any auto-incremented columns in the table, this returns the
value generated for that column in the last INSERT or, UPDATE operation.
4
rowcount
This returns the number of rows returned/updated in case of SELECT and UPDATE operations.
5
statement
This property returns the last executed statement.
execute():
There are several methods to execute the query. The most common being the execute() method.
Its syntax is as follows:
Parameter Description
params (optional) Sequence or mapping used to provide values for the query
parameters.
This method executes the given database operation (query or command). The parameters found
in the tuple or dictionary params are bound to the variables in the operation.
Example
Return a list of your system's databases:
import mysql.connector
mycursor = mydb.cursor()
mycursor.execute("SHOW DATABASES")
for x in mycursor:
print(x)
Example
Let us create Database table EMPLOYEE −
import mysql.connector
close():
Syntax:
connection.close()
For a connection obtained from a connection pool, close() does not actually close it but returns it
to the pool and makes it available for subsequent connection requests.
INSERT Operation
It is required when you want to create your records into a database table.
Example
The following example, executes SQL INSERT statement to create a record into EMPLOYEE table −
import mysql.connector
Once our database connection is established, you are ready to make a query into this database.
You can use either fetchone() method to fetch single record or fetchall() method to fetech
multiple values from a database table.
• fetchone() − It fetches the next row of a query result set. A result set is an object that is
returned when a cursor object is used to query a table.
• fetchall() − It fetches all the rows in a result set. If some rows have already been
extracted from the result set, then it retrieves the remaining rows from the result set.
• rowcount − This is a read-only attribute and returns the number of rows that were
affected by an execute() method.
Example
The following procedure queries all the records from EMPLOYEE table having salary more than 1000 −
import mysql.connector
Update Operation
UPDATE Operation on any database means to update one or more records, which are already
available in the database.
The following procedure updates all the records having SEX as 'M'. Here, we increase AGE of all
the males by one year.
import mysql.connector
DELETE Operation
DELETE operation is required when you want to delete some records from your database.
Following is the procedure to delete all the records from EMPLOYEE where AGE is more than 20
import mysql.connector
Model
First off, what is a model? Well, it’s something that represents an object. The object can be stored
in a database. We can fetch it from there, modify and push back.
How is a model different from a Python dictionary then? Easy. Dictionaries know nothing about
where the data came from, what parts of it are important for us, how the values should be
converted to and fro, and how should the data be validated before it is stored somewhere. A
model of an apple does know what properties should an object have to be a Proper Apple; what
can be done the apple so that it does not stop being a Proper Apple; and where does the apple
belong so it won’t be in the way when it isn’t needed anymore.
In other words, the model is an answer to questions what, where and how about a document.
And a dictionary is a document (or, more precisely, a simple representation of the document in
given environment).
Defining models
class Thing(Model):
pass
Just a Python class. Not very useful as it does not specify any property. Let’s observe the object
thoroughly and conclude that colour is an important distinctive feature of this... um, sort of thing:
class Thing(Model):
colour = Property()
Great, now that’s a model. It recognizes a property as significant. Now we can compare, search
and distinguish objects by colour (and its presence or lack). Obviously, if colour is an applicable
property for an object, then it belongs to this model.
A more complete example which will look familiar to those who had ever used an ORM (e.g. the
Django one):
import datetime
class Country(Model):
def __unicode__(self):
return self.name
class Meta:
class Person(Model):
first_name = Property(required=True)
last_name = Property(required=True)
gender = Property()
birth_date = Date()
def __unicode__(self):
@property
def age(self):
@property
def full_name(self):
class Meta:
The interesting part is the Meta subclass. It contains a must_have attribute which actually binds
the model to a subset of data in the storage. {'first_name__exists': True} states that a data
row/document/... must have the field first_name defined (not necessarily non-empty). You can
easily define any other query conditions (currently with respect to the backend’s syntax but we
hope to unify things). When you create an empty model instance, it will have all the “must haves”
pre-filled if they are not complex lookups (e.g. Country will have its type set to True, but we
cannot do that with Person‘s constraints).