0% found this document useful (0 votes)
4 views10 pages

Advance Python Unit - 4

This document provides a comprehensive guide on how to interact with a MySQL database using Python, including environment setup, creating connections, and performing various database operations such as creating databases, tables, and executing CRUD operations. It covers the use of MySQL Connector/Python, methods and properties of cursor objects, and defining models for data representation. The document also includes code examples for each operation to facilitate understanding and implementation.

Uploaded by

disecek477
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views10 pages

Advance Python Unit - 4

This document provides a comprehensive guide on how to interact with a MySQL database using Python, including environment setup, creating connections, and performing various database operations such as creating databases, tables, and executing CRUD operations. It covers the use of MySQL Connector/Python, methods and properties of cursor objects, and defining models for data representation. The document also includes code examples for each operation to facilitate understanding and implementation.

Uploaded by

disecek477
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

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.

To access the MySQL database from Python, you


need a database driver. MySQL Connector/Python is
a standardized database driver provided by MySQL.

MySQL Connector/Python supports almost all


features provided by MySQL version 5.7.

For
or using MySQL with python you should have
MySQL
SQL installed on your computer.

You can download a free MySQL database at https://www.mysql.com/downloads/.

Form Download tab select MySQL Community(GPL) Downloads


The following screen will appear. Select MySQL Installer for Windows.

Install MySQL installer.

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:

C:\Programs Flies\Python\Python37-32\>python -m pip install mysql-connector-python

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.

Use the username and password from your MySQL 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()

mycursor.execute("CREATE DATABASE mydatabase")

cursor():
You can create cursor object using the cursor method of the connection object/class.

For example: cursor = conn.cursor()

Methods

Following are the various methods provided by the Cursor class/object.

Sr.No Method & Description

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

Following are the properties of the Cursor class −

Sr.No Property & Description

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:

cursor.execute(operation(query), params=None, multi=False)

Parameter Description

query (required) SQL query or command to execute

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.

Check if Database Exists


You can check if a database exists by listing all databases in your system by using the "SHOW
DATABASES" statement:

Example
Return a list of your system's databases:

import mysql.connector

mydb = mysql.connector.connect(host="localhost", user="yourusername", password="yourpassword")

mycursor = mydb.cursor()

mycursor.execute("SHOW DATABASES")

for x in mycursor:
print(x)

Creating Database Table


Once a database connection is established, we are ready to create tables or records into the
database tables using execute method of the created cursor.

Example
Let us create Database table EMPLOYEE −
import mysql.connector

# Open database connection


db = mysql.connector.connect(host="localhost",user="root",password="jkmbca",database="mydata")

# prepare a cursor object using cursor() method


cursor = db.cursor()

# Drop table if it already exist using execute() method.


cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
# Create table as per requirement
sql = """CREATE TABLE EMPLOYEE (
FIRST_NAME CHAR(20) NOT NULL,
LAST_NAME CHAR(20),
AGE INT,
SEX CHAR(1),
INCOME FLOAT )"""
cursor.execute(sql)

# disconnect from server


db.close()

close():
Syntax:

connection.close()

close() is a synonym for disconnect().

When the MySQL-processing is done one should close the connection.

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

# Open database connection


db = mysql.connector.connect(host="localhost",user="root",password="jkmbca",database="mydata")

# prepare a cursor object using cursor() method


cursor = db.cursor()

# Prepare SQL query to INSERT a record into the database.


sql = """INSERT INTO EMPLOYEE(FIRST_NAME,
LAST_NAME, AGE, SEX, INCOME)
VALUES ('Mac', 'Mohan', 20, 'M', 2000)"""
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()

# disconnect from server


db.close()
READ Operation
READ Operation on any database means to fetch some useful information from the database.

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

# Open database connection


db = mysql.connector.connect(host="localhost",user="root",password="jkmbca",database="mydata")
# prepare a cursor object using cursor() method
cursor = db.cursor()
sql = "SELECT * FROM EMPLOYEE \
WHERE INCOME > '%d'" % (1000)
try:
# Execute the SQL command
cursor.execute(sql)
# Fetch all the rows in a list of lists.
results = cursor.fetchall()
for row in results:
fname = row[0]
lname = row[1]
age = row[2]
sex = row[3]
income = row[4]
# Now print fetched result
print (fname,lname,age,sex,income)
except:
print ("Error: unable to fecth data")

# disconnect from server


db.close()

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

# Open database connection


db = mysql.connector.connect(host="localhost",user="root",password="jkmbca",database="mydata")

# prepare a cursor object using cursor() method


cursor = db.cursor()

# Prepare SQL query to UPDATE required records


sql = "UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = '%c'" % ('M')
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()

# disconnect from server


db.close()

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

# Open database connection


db = mysql.connector.connect(host="localhost",user="root",password="jkmbca",database="mydata")

# prepare a cursor object using cursor() method


cursor = db.cursor()

# Prepare SQL query to DELETE required records


sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (20)
try:
# Execute the SQL command
cursor.execute(sql)

# Commit your changes in the database


db.commit()
except:
# Rollback in case there is any error
db.rollback()

# disconnect from server


db.close()

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

The simplest possible model:

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

from pymodels import *

class Country(Model):

name = Property(unicode) # any Python type; default is unicode

def __unicode__(self):

return self.name

class Meta:

must_have = {'type': 'country'}

class Person(Model):

first_name = Property(required=True)

last_name = Property(required=True)
gender = Property()

birth_date = Date()

birth_place = Property(Country) # reference to another model

def __unicode__(self):

return self.full_name # full_name is a dynamic attr, see below

@property

def age(self):

return (datetime.datetime.now().date() - self.birth_date).days / 365

@property

def full_name(self):

return '%s %s' % (self.first_name, self.last_name)

class Meta:

must_have = {'first_name__exists': True, 'last_name__exists': True}

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).

You might also like