The Python programming language typical for database lines is the Python DB-API. The majority of Python database interfaces go after this normal. You can select the correct database for your application. Python Database API cause to be an array of database servers such as:
Here is the catalog of nearby Python database borders API. Users have to download a theoretical DB API component for each database user's state to admittance. For instance, if users desire to admission an Oracle database and a MySQL database, users must download equally the Oracle and the MySQL database modules.
The DB API provisions a minimal normal for working with files using Python design arrangements and syntax wherever attainable.
API incorporates the following-
We would learn each of the concepts using MySQL, so let us talk about MySQLdb module.
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.
Before proceeding, you ensure you have MySQLdb installed on your machine. Just type the adhering to your Python script and execute it:
#!/usr/bin/python import MySQLdb
If it produces the following result, then it means the MySQLdb module is not installed:
Traceback (most recent call last): File "test.py", line 3, in import MySQLdb ImportError: No module named MySQLdb
To install the MySQLdb module, use the following command:
Traceback (most recent call last): File "test.py", line 3, in import MySQLdba ImportError: No module named MySQLdb
Note- Make sure you have root privilege to install the above module.
Before connecting to a MySQL database, make sure of the followings-
Following is the example of connecting with MySQL database "TESTDB"
#!/usr/bin/python import MySQLdb # Open database connection db = MySQLdb.connect("localhost","testuser","test123","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()
While running this script, it is producing the following result in my Linux machine.
Database version : 5.0.45
If a connection is launched with the data source, then a Connection Object is returned and saved into DB for further use, otherwise, DB is set to None. Next, DB object is used to create a cursor object, which in turn is utilized to execute SQL queries. Finally, before coming out, it makes sure that the database connection is closed and resources are released.
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.
Let us create a Database table EMPLOYEE?
#!/usr/bin/python import MySQLdb # Open database connection db = MySQLdb.connect("localhost","testuser","test123","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 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()
It is required when you want to create your records into a database table.
The following example, executes SQL INSERT statement to create a record into the EMPLOYEE table:
#!/usr/bin/python import MySQLdb # Open database connection db = MySQLdb.connect("localhost","testuser","test123","TESTDB" ) # 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()
The above example can be written as follows to create SQL queries dynamically:
#!/usr/bin/python import MySQLdb # Open database connection db = MySQLdb.connect("localhost","testuser","test123","TESTDB" ) # 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()
Following code, segment is another form of execution where you can pass parameters directly
.................................. user_id = "test123" password = "password" con.execute('insert into Login values("%s", "%s")' % \ (user_id, password)) ..................................
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 a single record or fetchall() method to fetch multiple values from a database table.
The following procedure queries all the records from the EMPLOYEE table having salary more than 1000
#!/usr/bin/python import MySQLdb # Open database connection db = MySQLdb.connect("localhost","testuser","test123","TESTDB" ) # 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=%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()
This will produce the following result
fname=Mac, lname=Mohan, age=20, sex=M, income=2000
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.
#!/usr/bin/python import MySQLdb # Open database connection db = MySQLdb.connect("localhost","testuser","test123","TESTDB" ) # 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 is necessitated 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:
#!/usr/bin/python import MySQLdb # Open database connection db = MySQLdb.connect("localhost","testuser","test123","TESTDB" ) # 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()
Transactions are a mechanism that ensures data consistency. Do transactions have the following four properties-
The Python DB API 2.0 provides two methods to either commit or roll back a transaction.
You already know how to implement transactions. Here is again a similar example
# 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()
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.
Here is a simple example to call commit method.
db.commit()
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.
Here is a simple example to call rollback() method.
db.rollback()
To disconnect Database connection, use close() method.
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's lower-level implementation details, your application would be better off calling commit or rollback explicitly.
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.
Sr.No. | Exception & Description |
1 | Warning Used for non-fatal issues. Must subclass StandardError. |
2 | Error Base class for errors. Must subclass StandardError. |
3 | InterfaceError Used for errors in the database module, not the database itself. Must subclass Error. |
4 | DatabaseError Used for errors in the database. Must subclass Error. |
5 | DataError Subclass of DatabaseError refers to errors in the data. |
6 | OperationalError Subclass of DatabaseError 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. |
7 | IntegrityError Subclass of DatabaseError for situations that would damage the relational integrity, such as uniqueness constraints or foreign keys. |
8 | InternalError Subclass of DatabaseError refers to errors internal to the database module, such as a cursor no longer being active. |
9 | ProgrammingError Subclass of DatabaseError refers to errors such as a bad table name and other things that can safely be blamed on you. |
10 | NotSupportedError Subclass of DatabaseError refers to trying to call unsupported functionality. |
Users Python scripts should grip these errors, other than before using some of the above exceptions, ensure users MySQLdb have reinforced for that exception. Users can get additional information concerning them by reading the DB API 2.0 specification.
Here at Intellinuts, we have created a complete Python tutorial for Beginners to get started in Python.