Python To MySql Connection
Python To MySql Connection
Python To MySql Connection
DATABASE
Introduction
• The Python standard for database interfaces is the Python DB-API.
Most Python database interfaces adhere to this standard.
• We can choose the right database for our application. Python
Database API supports a wide range of database servers such as −
• GadFly
• mSQL
• MySQL
• PostgreSQL
• Microsoft SQL Server 2000
• Informix
• Interbase
• Oracle
• Sybase
Download DB API
You must download a separate DB API module for each database
you need to access. For example, if you need to access an Oracle
database as well as a MySQL database, you must 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.
This API includes the following −
• Importing the API module.
• Acquiring a connection with the database.
• Issuing SQL statements and stored procedures.
• Closing the connection
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 do I Install MySQLdb?
Before proceeding, you make sure you have MySQLdb installed on
your machine. 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
Connector for Python
Installing Connector/Python on Microsoft Windows
Managing all of your MySQL products, including MySQL
Connector/Python, with MySQL Installer is the
recommended approach. It handles all requirements
and prerequisites, configurations, and upgrades.
15
Python DB-API
Connection Data Objects Description
close Closes the connection to the database.
commit Commits (saves) a transaction (i.e., interaction with a database through SQL keywords
and commands).
rollback Exits a pending transaction without saving changes. Returns the user to the beginning
of the transaction.
cursor Returns a new Cursor object or the current connection.
executemany( operation, Executes a database query or command against a set of parameters. Return values not
defined.
parameters )
fetchone Returns the next row of a query result.
fetchmany( size ) Returns a set of rows—defined in the parameter—for a query result set.
16 fetchall
Returns all the rows of a query result set.