Complete Guide For Python Programming (2015)

INSTANCES

Class is a data structure definition type, while an instance is a declaration of a variable of that type. Or you can say that instances are classes which are brought to life. Instances are the objects which are used primarily during execution, and all instances are of type "instance."

Creating Instances by Invoking Class Object

Most languages provide a new keyword to create an instance of a class. The python's approach is much simpler. Once a class has been defined in python, creating an instance is no more difficult. Using instantiation of the function operator.

For Example:

>>> class MyTeam: # define class

… pass

>>> myInstance = MyTeam() # instantiate class

>>> type(MyTeam) # class is of class type

<type 'class'>

>>> type(myInstance) # instance is of instance type

<type 'instance'>

Using the term "type" in Python is different from the instance being of the type of class it was created from. An object's type dictates the behavioral properties of such objects in the Python system, and these types are a subset of all types, which Python supports. User-defined "types" such as classes are categorized in the same manner. Classes share the same type, but have different IDs and values. All classes are defined with the same syntax, so they can be instantiated, and all have the same core properties. Classes are unique objects, which are differ only in definition, hence they are all the same "type" in Python.

Instance Attributes

Instances have only data attributes and these are simply the data values which you want to be associated with a particular instance of any class. They are accessible via the familiar dotted-attribute notation. These values are independent of any other instance or the class it was instantiated from. If any instance is deallocated, then its attributes are also deallocated.

"Instantiating" Instance Attributes

Instance attributes can be set any time after an instance has been created, in any piece of code that has access to the instance. However, one of the key places where such attributes are set is in the constructor, __init__ ().

Constructor First Place to Set Instance Attributes

The constructor is the earliest place that instance attributes can be set because __init__ () is the first method called after instance objects have been created. There is no earlier opportunity to set instance attributes. Once __init__ () has finished execution, the instance object is returned, completing the instantiation process.

Default Arguments Provide Default Instance Setup

One can also use __init__ () along with default arguments to provide an effective way in preparing an instance for use. In most of the cases, the default values represent the most common cases for setting up instance attributes, and such use of default values precludes them from having to be given explicitly to the constructor.

Built-in Type Attributes

Built-in types also have attributes, and although they are technically not class instance attributes, they are sufficiently similar to get a brief mention here. Type attributes do not have an attribute dictionary like classes and instances (__dict__), so how do we figure out what attributes built-in types have? The convention for built-in types is to use two special attributes, __methods__ and __members__, to outline any methods and/or data attributes.

Instance Attributes vs. Class Attributes

Class attributes are simply data values which are associated with a class and with not any particular instances. Such values are also referred to as static members because their values remain constant, even if a class is invoked due to instantiation multiple times. No matter what, static members maintain their values independent of instances unless explicitly changed. Comparing instance attributes to class attributes is just similar to comparing automatic and static variables. Their main aspect is that you can access a class attribute with either the class or an instance, while the instance does not have an attribute with the same name.

Python Database Access

The standard database used for Python is DB-API. Most Python database interfaces adhere to this standard. You can choose the right database for your application. Python Database API supports a wide range of database servers such as, GadFly, mSQL, MySQL, PostgreSQL, Microsoft SQL Server 11000, Informix, Interbase, Oracle, Sybase. You must download a separate DB API module for each database that you need to access. For example, if you need to access an Oracle database as well as a MySQL database, then you need to download both the Oracle and the MySQL database modules.

The DB API provides a minimal standard for working with databases using Python structures and syntax wherever possible.

The API includes:

• Importing the API module.

• Acquiring a connection with the database.

• Issuing SQL statements and stored procedures.

• Closing the connection

We would learn all the concepts using MySQL, so let's talk about MySQLdb module only.

What is MySQLdb?

MySQLdb is an interface for connecting to a MySQL database server from Python. It implements the Python Database API v2.0 and is built on top of the MySQL C API.

How to install MySQLdb?

Before proceeding, you make sure you have MySQLdb installed on your Tomhine. Just type the following in your Python script and execute it:

#!/usr/bin/python

import MySQLdb

If it produces the following result, then it means MySQLdb module is not installed:

Traceback (most recent call last):

File "test.py", line 3, in <module>

import MySQLdb

ImportError: No module named MySQLdb

To install MySQLdb module, download it from MySQLdb Download page and proceed as follows:

$ gunzip MySQL-python-1.2.2.tar.gz

$ tar -xvf MySQL-python-1.2.2.tar

$ cd MySQL-python-1.2.2

$ python setup.py build

$ python setup.py install

Database Connection:

Before connecting to a MySQL database, you need to make sure of the followings points given below:

• You have created a database TESTDB.

• You have created a table STAFF in TESTDB.

• This table is having fields FIRST_NAME, LAST_NAME, AGE, SEX and INCOME.

• User ID "abctest" and password "python121" are set to access TESTDB.

• Python module MySQLdb is installed properly on your Tomhine.

• You have gone through MySQL tutorial to understand MySQL Basics.

For Example:

Connecting with MySQL database "TESTDB":

#!/usr/bin/python

import MySQLdb

# Open database connection

db = MySQLdb.connect("localhost","abctest","python121","TESTDB")

# prepare a cursor object using cursor() method

cursor = db.cursor()

# execute SQL query using execute() method.

cursor.execute("SELECT VERSION()")

# Fetch a single row using fetchone() method.

data = cursor.fetchone()

print "Database version : %s " % data

# disconnect from server

db.close()

Output:

Database version : 5.0.45

Creating Database Table:

Once a database connection is established, you can easily create tables or records into the database using execute method.

Example for creating Database table STAFF:

#!/usr/bin/python

import MySQLdb

# Open database connection

db = MySQLdb.connect("localhost","abctest","python121","TESTDB")

# 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 STAFF")

# Create table as per requirement sql = """CREATE TABLE STAFF (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()

INSERT Operation:

INSERT operation is required when you want to create your records into a database table.

Example to create a record into STAFF table:

#!/usr/bin/python

import MySQLdb

# Open database connection

db = MySQLdb.connect("localhost","abctest","python121","TESTDB" )

# prepare a cursor object using cursor() method

cursor = db.cursor()

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

sql = """INSERT INTO STAFF(FIRST_NAME,LAST_NAME, AGE, SEX, INCOME)

VALUES ('Tom', 'David', 20, 'M', 11000)"""

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

Above example can be written as follows to create SQL queries dynamically:

#!/usr/bin/python

import MySQLdb

# Open database connection

db = MySQLdb.connect("localhost","abctest","python121","TESTDB" )

# prepare a cursor object using cursor() method

cursor = db.cursor()

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

sql = "INSERT INTO STAFF(FIRST_NAME, \LAST_NAME, AGE, SEX, INCOME) \

VALUES ('%s', '%s', '%d', '%c', '%d' )" % \ ('Tom', 'David', 20, 'M', 11000)

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 database means to fetch some useful information from the database. Once our database connection is established, we are ready to make a query into this database. We can use either fetchone() method to fetch single record or fetchall() method to fetech multiple values from a database table.

• fetchone(): This method 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(): This method fetches all the rows in a result set. If some rows have already been extracted from the result set, the fetchall() method 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 to query all the records from STAFF table having salary more than 5000:

#!/usr/bin/python

import MySQLdb

# Open database connection

db = MySQLdb.connect("localhost","abctest","python121","TESTDB" )

# prepare a cursor object using cursor() method

cursor = db.cursor()

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

sql = "SELECT * FROM STAFF \

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=%s,lname=%s,age=%d,sex=%s,income=%d" % \

(fname, lname, age, sex, income )

except:

print "Error: unable to fecth data"

# disconnect from server

db.close()

Output:

fname=Tom, lname=David, age=20, sex=M, income=11000

Update Operation:

UPDATE Operation on any database means to update one or more records, which are already available in the database. Following is the procedure to update all the records having SEX as 'M'. Here, we will increase AGE of all the males by one year.

For Example:

#!/usr/bin/python

import MySQLdb

# Open database connection

db = MySQLdb.connect("localhost","abctest","python121","TESTDB" )

# prepare a cursor object using cursor() method

cursor = db.cursor()

# Prepare SQL query to UPDATE required records

sql = "UPDATE STAFF 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 STAFF where AGE is more than 20:

For Example:

#!/usr/bin/python

import MySQLdb

# Open database connection

db = MySQLdb.connect("localhost","abctest","python121","TESTDB" )

# prepare a cursor object using cursor() method

cursor = db.cursor()

# Prepare SQL query to DELETE required records

sql = "DELETE FROM STAFF 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()

Performing Transactions:

Transactions are a mechanism that ensures consistency of data. Transactions should have the following properties:

• Atomicity: Either a transaction completes or nothing happens at all.

• Consistency: A transaction must start in a consistent state and leave the system in a consistent state.

• Isolation: Intermediate results of a transaction are not visible outside the current transaction.

• Durability: Once a transaction was committed, the effects are persistent, even after a system failure.

The Python DB API 2.0 provides two methods to either commit or rollback a transaction.

For Example:

# Prepare SQL query to DELETE required records

sql = "DELETE FROM STAFF 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()

COMMIT Operation:

Commit is the operation, which gives a green signal to database to finalize the changes, and after this operation, no change can be reverted back.

For Example:

db.commit()

ROLLBACK Operation:

If you are not satisfied with one or more of the changes and you want to revert back those changes completely, then use rollback() method.

For Example:

db.rollback()

Disconnecting Database:

To disconnect Database connection, use close() method.

For Example:

db.close()

If the connection to a database is closed by the user with the close() method, any outstanding transactions are rolled back by the DB. However, instead of depending on any of DB lower level implementation details, your application would be better off calling commit or rollback explicitly.

Handling Errors:

There are many sources of errors. A few examples are a syntax error in an executed SQL statement, a connection failure, or calling the fetch method for an already canceled or finished statement handle. The DB API defines a number of errors that must exist in each database module. The following table lists these exceptions.

Exception Description

Warning Used for non-fatal issues. Must subclass StandardError.

Error Base class for errors. Must subclass StandardError.

InterfaceError

Used for errors in the database module, not the database itself. Must subclass Error.

DatabaseError

Used for errors in the database. Must subclass Error. DataError Subclass of DatabaseError that refers to errors in the data.

OperationalError

Subclass of DatabaseError that refers to errors such as the loss of a connection to the database. These errors are generally outside of the control of the Python scripter.

IntegrityError

Subclass of DatabaseError for situations that would damage the relational integrity, such as uniqueness constraints or foreign keys.

InternalError

Subclass of DatabaseError that refers to errors internal to the database module, such as a cursor no longer being active.

ProgrammingError

Subclass of DatabaseError that refers to errors such as a bad table name and other things that can safely be blamed on you.

NotSupportedError

Subclass of DatabaseError that refers to trying to call unsupported functionality.

Your Python scripts should handle these errors, but before using any of the above exceptions, make sure your MySQLdb has support for that exception. You can get more information about them by reading the DB API 2.0 specification.