SlideShare a Scribd company logo
http://www.tutorialspoint.com/python/python_database_access.htm Copyright © tutorialspoint.com
PYTHON MYSQL DATABASE ACCESS
The Pythonstandard for database interfaces is the PythonDB-API. Most Pythondatabase interfaces adhere to
this standard.
Youcanchoose the right database for your application. PythonDatabase API supports a wide range of database
servers:
GadFly
mSQL
MySQL
PostgreSQL
Microsoft SQL Server 2000
Informix
Interbase
Oracle
Sybase
Here is the list of available Pythondatabase interfaces: PythonDatabase Interfaces and APIs .Youmust
download a separate DB API module for eachdatabase youneed to access. For example, if youneed to access
anOracle database as wellas a MySQL database, youmust download boththe Oracle and the MySQL database
modules.
The DB API provides a minimalstandard for working withdatabases using Pythonstructures and syntax
wherever possible. This API includes the following:
Importing the API module.
Acquiring a connectionwiththe database.
Issuing SQL statements and stored procedures.
Closing the connection
We would learnallthe concepts using MySQL, so let's talk about MySQLdb module only.
What is MySQLdb?
MySQLdb is aninterface for connecting to a MySQL database server fromPython. It implements the Python
Database API v2.0 and is built ontop of the MySQL C API.
How do I install the MySQLdb?
Before proceeding, youmake sure youhave MySQLdb installed onyour machine. Just type the following inyour
Pythonscript and execute it:
#!/usr/bin/python
import MySQLdb
If it produces the following result, thenit 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 installMySQLdb module, download it fromMySQLdb 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
Note: Make sure youhave root privilege to installabove module.
Database Connection:
Before connecting to a MySQL database, make sure of the followings:
Youhave created a database TESTDB.
Youhave created a table EMPLOYEE inTESTDB.
This table is having fields FIRST_NAME, LAST_NAME, AGE, SEX and INCOME.
User ID "testuser" and password "test123" are set to access TESTDB.
Pythonmodule MySQLdb is installed properly onyour machine.
Youhave gone throughMySQL tutorialto understand MySQL Basics.
Example:
Following is the example of connecting withMySQL 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 inmy Linux machine.
Database version : 5.0.45
If a connectionis established withthe datasource, thena ConnectionObject 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, whichinturnis
used to execute SQL queries. Finally, before coming out, it ensures that database connectionis closed and
resources are released.
Creating Database Table:
Once a database connectionis established, we are ready to create tables or records into the database tables
using execute method of the created cursor.
Example:
First, let's create 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()
INSERT Operation:
INSERT operationis required whenyouwant to create your records into a database table.
Example:
Following is the example, whichexecutes SQL INSERT statement to create a record into 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()
Above example canbe writtenas 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 ('%s', '%s', '%d', '%c', '%d' )" % 
('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()
Example:
Following code segment is another formof executionwhere youcanpass parameters directly:
..................................
user_id = "test123"
password = "password"
con.execute('insert into Login values("%s", "%s")' % 
(user_id, password))
..................................
READ Operation:
READ Operationonany databasse means to fetchsome usefulinformationfromthe database.
Once our database connectionis established, we are ready to make a query into this database. We canuse either
fetchone() method to fetchsingle record or fetchall() method to fetechmultiple values froma database table.
fetchone(): This method fetches the next row of a query result set. A result set is anobject that is
returned whena cursor object is used to query a table.
fetchall(): This method fetches allthe rows ina result set. If some rows have already beenextracted
fromthe result set, the fetchall() method retrieves the remaining rows fromthe result set.
rowcount: This is a read-only attribute and returns the number of rows that were affected by an
execute() method.
Example:
Following is the procedure to query allthe records fromEMPLOYEE table having salary more than1000:
#!/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 = "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 willproduce the following result:
fname=Mac, lname=Mohan, age=20, sex=M, income=2000
Update Operation:
UPDATE Operationonany databasse means to update one or more records, whichare already available inthe
database. Following is the procedure to update allthe records having SEX as 'M'. Here, we willincrease AGE of
allthe males by one year.
Example:
#!/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:
DELETE operationis required whenyouwant to delete some records fromyour database. Following is the
procedure to delete allthe records fromEMPLOYEE where AGE is more than20:
Example:
#!/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()
Performing Transactions:
Transactions are a mechanismthat ensures data consistency. Transactions should have the following four
properties:
Atomicity: Either a transactioncompletes or nothing happens at all.
Consistency: A transactionmust start ina consistent state and leave the systemina consistent state.
Isolation: Intermediate results of a transactionare not visible outside the current transaction.
Durability: Once a transactionwas committed, the effects are persistent, evenafter a systemfailure.
The PythonDB API 2.0 provides two methods to either commit or rollback a transaction.
Example:
Youalready have seenhow we have implemented transations. Here is againsimilar 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 Operation:
Commit is the operation, whichgives a greensignalto database to finalize the changes, and after this operation,
no change canbe reverted back.
Here is a simple example to callcommit method.
db.commit()
ROLLBACK Operation:
If youare not satisfied withone or more of the changes and youwant to revert back those changes completely,
thenuse rollback() method.
Here is a simple example to callrollback() method.
db.rollback()
Disconnecting Database:
To disconnect Database connection, use close() method.
db.close()
If the connectionto a database is closed by the user withthe close() method, any outstanding transactions are
rolled back by the DB. However, instead of depending onany of DB lower levelimplementationdetails, your
applicationwould be better off calling commit or rollback explicitly.
Handling Errors:
There are many sources of errors. A few examples are a syntax error inanexecuted SQL statement, a
connectionfailure, or calling the fetchmethod for analready canceled or finished statement handle.
The DB API defines a number of errors that must exist ineachdatabase module. The following table lists these
exceptions.
Exception Description
Warning Used for non-fatalissues. Must subclass StandardError.
Error Base class for errors. Must subclass StandardError.
InterfaceError Used for errors inthe database module, not the database itself. Must subclass Error.
DatabaseError Used for errors inthe database. Must subclass Error.
DataError Subclass of DatabaseError that refers to errors inthe data.
OperationalError Subclass of DatabaseError that refers to errors suchas the loss of a connectionto the
database. These errors are generally outside of the controlof the Pythonscripter.
IntegrityError Subclass of DatabaseError for situations that would damage the relationalintegrity,
suchas uniqueness constraints or foreignkeys.
InternalError Subclass of DatabaseError that refers to errors internalto the database module, such
as a cursor no longer being active.
ProgrammingError Subclass of DatabaseError that refers to errors suchas a bad table name and other
things that cansafely be blamed onyou.
NotSupportedError Subclass of DatabaseError that refers to trying to callunsupported functionality.
Your Pythonscripts should handle these errors, but before using any of the above exceptions, make sure your
MySQLdb has support for that exception. Youcanget more informationabout themby reading the DB API 2.0
specification.

More Related Content

What's hot

Sequelize
SequelizeSequelize
Sequelize
Tarek Raihan
 
Php forum2015 tomas_final
Php forum2015 tomas_finalPhp forum2015 tomas_final
Php forum2015 tomas_final
Bertrand Matthelie
 
Using JSON with MariaDB and MySQL
Using JSON with MariaDB and MySQLUsing JSON with MariaDB and MySQL
Using JSON with MariaDB and MySQL
Anders Karlsson
 
DB2 Native XML
DB2 Native XMLDB2 Native XML
DB2 Native XML
Amol Pujari
 
Developing for Node.JS with MySQL and NoSQL
Developing for Node.JS with MySQL and NoSQLDeveloping for Node.JS with MySQL and NoSQL
Developing for Node.JS with MySQL and NoSQL
John David Duncan
 
Sqlxml vs xquery
Sqlxml vs xquerySqlxml vs xquery
Sqlxml vs xquery
Amol Pujari
 
The Ring programming language version 1.4.1 book - Part 8 of 31
The Ring programming language version 1.4.1 book - Part 8 of 31The Ring programming language version 1.4.1 book - Part 8 of 31
The Ring programming language version 1.4.1 book - Part 8 of 31
Mahmoud Samir Fayed
 
Load Data Fast!
Load Data Fast!Load Data Fast!
The Ring programming language version 1.6 book - Part 31 of 189
The Ring programming language version 1.6 book - Part 31 of 189The Ring programming language version 1.6 book - Part 31 of 189
The Ring programming language version 1.6 book - Part 31 of 189
Mahmoud Samir Fayed
 
Data Love Conference - Window Functions for Database Analytics
Data Love Conference - Window Functions for Database AnalyticsData Love Conference - Window Functions for Database Analytics
Data Love Conference - Window Functions for Database Analytics
Dave Stokes
 
Validating JSON -- Percona Live 2021 presentation
Validating JSON -- Percona Live 2021 presentationValidating JSON -- Percona Live 2021 presentation
Validating JSON -- Percona Live 2021 presentation
Dave Stokes
 
15 MySQL Basics #burningkeyboards
15 MySQL Basics #burningkeyboards15 MySQL Basics #burningkeyboards
15 MySQL Basics #burningkeyboards
Denis Ristic
 
The Ring programming language version 1.7 book - Part 32 of 196
The Ring programming language version 1.7 book - Part 32 of 196The Ring programming language version 1.7 book - Part 32 of 196
The Ring programming language version 1.7 book - Part 32 of 196
Mahmoud Samir Fayed
 
Datacon LA - MySQL without the SQL - Oh my!
Datacon LA - MySQL without the SQL - Oh my! Datacon LA - MySQL without the SQL - Oh my!
Datacon LA - MySQL without the SQL - Oh my!
Dave Stokes
 
The Ring programming language version 1.5.2 book - Part 28 of 181
The Ring programming language version 1.5.2 book - Part 28 of 181The Ring programming language version 1.5.2 book - Part 28 of 181
The Ring programming language version 1.5.2 book - Part 28 of 181
Mahmoud Samir Fayed
 
Discover the Power of the NoSQL + SQL with MySQL
Discover the Power of the NoSQL + SQL with MySQLDiscover the Power of the NoSQL + SQL with MySQL
Discover the Power of the NoSQL + SQL with MySQL
Dave Stokes
 
Lab1-DB-Cassandra
Lab1-DB-CassandraLab1-DB-Cassandra
Lab1-DB-Cassandra
Lilia Sfaxi
 
Store and Process Big Data with Hadoop and Cassandra
Store and Process Big Data with Hadoop and CassandraStore and Process Big Data with Hadoop and Cassandra
Store and Process Big Data with Hadoop and Cassandra
Deependra Ariyadewa
 
CQL performance with Apache Cassandra 3.0 (Aaron Morton, The Last Pickle) | C...
CQL performance with Apache Cassandra 3.0 (Aaron Morton, The Last Pickle) | C...CQL performance with Apache Cassandra 3.0 (Aaron Morton, The Last Pickle) | C...
CQL performance with Apache Cassandra 3.0 (Aaron Morton, The Last Pickle) | C...
DataStax
 
Learn PHP Lacture2
Learn PHP Lacture2Learn PHP Lacture2
Learn PHP Lacture2
ADARSH BHATT
 

What's hot (20)

Sequelize
SequelizeSequelize
Sequelize
 
Php forum2015 tomas_final
Php forum2015 tomas_finalPhp forum2015 tomas_final
Php forum2015 tomas_final
 
Using JSON with MariaDB and MySQL
Using JSON with MariaDB and MySQLUsing JSON with MariaDB and MySQL
Using JSON with MariaDB and MySQL
 
DB2 Native XML
DB2 Native XMLDB2 Native XML
DB2 Native XML
 
Developing for Node.JS with MySQL and NoSQL
Developing for Node.JS with MySQL and NoSQLDeveloping for Node.JS with MySQL and NoSQL
Developing for Node.JS with MySQL and NoSQL
 
Sqlxml vs xquery
Sqlxml vs xquerySqlxml vs xquery
Sqlxml vs xquery
 
The Ring programming language version 1.4.1 book - Part 8 of 31
The Ring programming language version 1.4.1 book - Part 8 of 31The Ring programming language version 1.4.1 book - Part 8 of 31
The Ring programming language version 1.4.1 book - Part 8 of 31
 
Load Data Fast!
Load Data Fast!Load Data Fast!
Load Data Fast!
 
The Ring programming language version 1.6 book - Part 31 of 189
The Ring programming language version 1.6 book - Part 31 of 189The Ring programming language version 1.6 book - Part 31 of 189
The Ring programming language version 1.6 book - Part 31 of 189
 
Data Love Conference - Window Functions for Database Analytics
Data Love Conference - Window Functions for Database AnalyticsData Love Conference - Window Functions for Database Analytics
Data Love Conference - Window Functions for Database Analytics
 
Validating JSON -- Percona Live 2021 presentation
Validating JSON -- Percona Live 2021 presentationValidating JSON -- Percona Live 2021 presentation
Validating JSON -- Percona Live 2021 presentation
 
15 MySQL Basics #burningkeyboards
15 MySQL Basics #burningkeyboards15 MySQL Basics #burningkeyboards
15 MySQL Basics #burningkeyboards
 
The Ring programming language version 1.7 book - Part 32 of 196
The Ring programming language version 1.7 book - Part 32 of 196The Ring programming language version 1.7 book - Part 32 of 196
The Ring programming language version 1.7 book - Part 32 of 196
 
Datacon LA - MySQL without the SQL - Oh my!
Datacon LA - MySQL without the SQL - Oh my! Datacon LA - MySQL without the SQL - Oh my!
Datacon LA - MySQL without the SQL - Oh my!
 
The Ring programming language version 1.5.2 book - Part 28 of 181
The Ring programming language version 1.5.2 book - Part 28 of 181The Ring programming language version 1.5.2 book - Part 28 of 181
The Ring programming language version 1.5.2 book - Part 28 of 181
 
Discover the Power of the NoSQL + SQL with MySQL
Discover the Power of the NoSQL + SQL with MySQLDiscover the Power of the NoSQL + SQL with MySQL
Discover the Power of the NoSQL + SQL with MySQL
 
Lab1-DB-Cassandra
Lab1-DB-CassandraLab1-DB-Cassandra
Lab1-DB-Cassandra
 
Store and Process Big Data with Hadoop and Cassandra
Store and Process Big Data with Hadoop and CassandraStore and Process Big Data with Hadoop and Cassandra
Store and Process Big Data with Hadoop and Cassandra
 
CQL performance with Apache Cassandra 3.0 (Aaron Morton, The Last Pickle) | C...
CQL performance with Apache Cassandra 3.0 (Aaron Morton, The Last Pickle) | C...CQL performance with Apache Cassandra 3.0 (Aaron Morton, The Last Pickle) | C...
CQL performance with Apache Cassandra 3.0 (Aaron Morton, The Last Pickle) | C...
 
Learn PHP Lacture2
Learn PHP Lacture2Learn PHP Lacture2
Learn PHP Lacture2
 

Similar to Python database access

RMySQL Tutorial For Beginners
RMySQL Tutorial For BeginnersRMySQL Tutorial For Beginners
RMySQL Tutorial For Beginners
Rsquared Academy
 
PHP - Getting good with MySQL part II
 PHP - Getting good with MySQL part II PHP - Getting good with MySQL part II
PHP - Getting good with MySQL part II
Firdaus Adib
 
Python with MySql.pptx
Python with MySql.pptxPython with MySql.pptx
Python with MySql.pptx
Ramakrishna Reddy Bijjam
 
Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursors
info_zybotech
 
Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursors
info_zybotech
 
Mysql python
Mysql pythonMysql python
Mysql python
Janu Jahnavi
 
Mysql python
Mysql pythonMysql python
Mysql python
Janu Jahnavi
 
Interfacing python to mysql (11363255151).pptx
Interfacing python to mysql (11363255151).pptxInterfacing python to mysql (11363255151).pptx
Interfacing python to mysql (11363255151).pptx
cavicav231
 
Python my SQL - create table
Python my SQL - create tablePython my SQL - create table
Python my SQL - create table
Learnbay Datascience
 
JDBC for CSQL Database
JDBC for CSQL DatabaseJDBC for CSQL Database
JDBC for CSQL Database
jitendral
 
All Things Open 2016 -- Database Programming for Newbies
All Things Open 2016 -- Database Programming for NewbiesAll Things Open 2016 -- Database Programming for Newbies
All Things Open 2016 -- Database Programming for Newbies
Dave Stokes
 
PHP with MySQL
PHP with MySQLPHP with MySQL
PHP with MySQL
wahidullah mudaser
 
Jdbc oracle
Jdbc oracleJdbc oracle
Jdbc oracle
yazidds2
 
harry presentation
harry presentationharry presentation
harry presentation
thembhani mapengo
 
Raj mysql
Raj mysqlRaj mysql
Raj mysql
firstplanet
 
Php classes in mumbai
Php classes in mumbaiPhp classes in mumbai
Php classes in mumbai
aadi Surve
 
MYSQL - PHP Database Connectivity
MYSQL - PHP Database ConnectivityMYSQL - PHP Database Connectivity
MYSQL - PHP Database Connectivity
V.V.Vanniaperumal College for Women
 
Introduction databases and MYSQL
Introduction databases and MYSQLIntroduction databases and MYSQL
Introduction databases and MYSQL
Naeem Junejo
 
PHP mysql Introduction database
 PHP mysql  Introduction database PHP mysql  Introduction database
PHP mysql Introduction database
Mudasir Syed
 
Node.js with MySQL.pdf
Node.js with MySQL.pdfNode.js with MySQL.pdf
Node.js with MySQL.pdf
SudhanshiBakre1
 

Similar to Python database access (20)

RMySQL Tutorial For Beginners
RMySQL Tutorial For BeginnersRMySQL Tutorial For Beginners
RMySQL Tutorial For Beginners
 
PHP - Getting good with MySQL part II
 PHP - Getting good with MySQL part II PHP - Getting good with MySQL part II
PHP - Getting good with MySQL part II
 
Python with MySql.pptx
Python with MySql.pptxPython with MySql.pptx
Python with MySql.pptx
 
Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursors
 
Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursors
 
Mysql python
Mysql pythonMysql python
Mysql python
 
Mysql python
Mysql pythonMysql python
Mysql python
 
Interfacing python to mysql (11363255151).pptx
Interfacing python to mysql (11363255151).pptxInterfacing python to mysql (11363255151).pptx
Interfacing python to mysql (11363255151).pptx
 
Python my SQL - create table
Python my SQL - create tablePython my SQL - create table
Python my SQL - create table
 
JDBC for CSQL Database
JDBC for CSQL DatabaseJDBC for CSQL Database
JDBC for CSQL Database
 
All Things Open 2016 -- Database Programming for Newbies
All Things Open 2016 -- Database Programming for NewbiesAll Things Open 2016 -- Database Programming for Newbies
All Things Open 2016 -- Database Programming for Newbies
 
PHP with MySQL
PHP with MySQLPHP with MySQL
PHP with MySQL
 
Jdbc oracle
Jdbc oracleJdbc oracle
Jdbc oracle
 
harry presentation
harry presentationharry presentation
harry presentation
 
Raj mysql
Raj mysqlRaj mysql
Raj mysql
 
Php classes in mumbai
Php classes in mumbaiPhp classes in mumbai
Php classes in mumbai
 
MYSQL - PHP Database Connectivity
MYSQL - PHP Database ConnectivityMYSQL - PHP Database Connectivity
MYSQL - PHP Database Connectivity
 
Introduction databases and MYSQL
Introduction databases and MYSQLIntroduction databases and MYSQL
Introduction databases and MYSQL
 
PHP mysql Introduction database
 PHP mysql  Introduction database PHP mysql  Introduction database
PHP mysql Introduction database
 
Node.js with MySQL.pdf
Node.js with MySQL.pdfNode.js with MySQL.pdf
Node.js with MySQL.pdf
 

More from Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai

PWM Arduino Experiment for Engineering pra
PWM Arduino Experiment for Engineering praPWM Arduino Experiment for Engineering pra
PWM Arduino Experiment for Engineering pra
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
Artificial Intelligence (AI) application in Agriculture Area
Artificial Intelligence (AI) application in Agriculture Area Artificial Intelligence (AI) application in Agriculture Area
Artificial Intelligence (AI) application in Agriculture Area
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
VLSI Design Book CMOS_Circuit_Design__Layout__and_Simulation
VLSI Design Book CMOS_Circuit_Design__Layout__and_SimulationVLSI Design Book CMOS_Circuit_Design__Layout__and_Simulation
VLSI Design Book CMOS_Circuit_Design__Layout__and_Simulation
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
Question Bank: Network Management in Telecommunication
Question Bank: Network Management in TelecommunicationQuestion Bank: Network Management in Telecommunication
Question Bank: Network Management in Telecommunication
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
INTRODUCTION TO CYBER LAW The Concept of Cyberspace Cyber law Cyber crime.pdf
INTRODUCTION TO CYBER LAW The Concept of Cyberspace Cyber law Cyber crime.pdfINTRODUCTION TO CYBER LAW The Concept of Cyberspace Cyber law Cyber crime.pdf
INTRODUCTION TO CYBER LAW The Concept of Cyberspace Cyber law Cyber crime.pdf
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
LRU_Replacement-Policy.pdf
LRU_Replacement-Policy.pdfLRU_Replacement-Policy.pdf
Network Management Principles and Practice - 2nd Edition (2010)_2.pdf
Network Management Principles and Practice - 2nd Edition (2010)_2.pdfNetwork Management Principles and Practice - 2nd Edition (2010)_2.pdf
Network Management Principles and Practice - 2nd Edition (2010)_2.pdf
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
Euler Method Details
Euler Method Details Euler Method Details
Mini Project fo BE Engineering students
Mini Project fo BE Engineering  students  Mini Project fo BE Engineering  students
Mini Project fo BE Engineering students
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
Mini Project for Engineering Students BE or Btech Engineering students
Mini Project for Engineering Students BE or Btech Engineering students Mini Project for Engineering Students BE or Btech Engineering students
Mini Project for Engineering Students BE or Btech Engineering students
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
Ballistics Detsils
Ballistics Detsils Ballistics Detsils
VLSI Design_LAB MANUAL By Umakant Gohatre
VLSI Design_LAB MANUAL By Umakant GohatreVLSI Design_LAB MANUAL By Umakant Gohatre
VLSI Design_LAB MANUAL By Umakant Gohatre
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
Cryptography and Network Security
Cryptography and Network SecurityCryptography and Network Security
cyber crime, Cyber Security, Introduction, Umakant Bhaskar Gohatre
cyber crime, Cyber Security, Introduction, Umakant Bhaskar Gohatre cyber crime, Cyber Security, Introduction, Umakant Bhaskar Gohatre
cyber crime, Cyber Security, Introduction, Umakant Bhaskar Gohatre
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
Image Compression, Introduction Data Compression/ Data compression, modelling...
Image Compression, Introduction Data Compression/ Data compression, modelling...Image Compression, Introduction Data Compression/ Data compression, modelling...
Image Compression, Introduction Data Compression/ Data compression, modelling...
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
Introduction Data Compression/ Data compression, modelling and coding,Image C...
Introduction Data Compression/ Data compression, modelling and coding,Image C...Introduction Data Compression/ Data compression, modelling and coding,Image C...
Introduction Data Compression/ Data compression, modelling and coding,Image C...
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
Python overview
Python overviewPython overview
Python numbers
Python numbersPython numbers
Python networking
Python networkingPython networking
Python multithreading
Python multithreadingPython multithreading

More from Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai (20)

PWM Arduino Experiment for Engineering pra
PWM Arduino Experiment for Engineering praPWM Arduino Experiment for Engineering pra
PWM Arduino Experiment for Engineering pra
 
Artificial Intelligence (AI) application in Agriculture Area
Artificial Intelligence (AI) application in Agriculture Area Artificial Intelligence (AI) application in Agriculture Area
Artificial Intelligence (AI) application in Agriculture Area
 
VLSI Design Book CMOS_Circuit_Design__Layout__and_Simulation
VLSI Design Book CMOS_Circuit_Design__Layout__and_SimulationVLSI Design Book CMOS_Circuit_Design__Layout__and_Simulation
VLSI Design Book CMOS_Circuit_Design__Layout__and_Simulation
 
Question Bank: Network Management in Telecommunication
Question Bank: Network Management in TelecommunicationQuestion Bank: Network Management in Telecommunication
Question Bank: Network Management in Telecommunication
 
INTRODUCTION TO CYBER LAW The Concept of Cyberspace Cyber law Cyber crime.pdf
INTRODUCTION TO CYBER LAW The Concept of Cyberspace Cyber law Cyber crime.pdfINTRODUCTION TO CYBER LAW The Concept of Cyberspace Cyber law Cyber crime.pdf
INTRODUCTION TO CYBER LAW The Concept of Cyberspace Cyber law Cyber crime.pdf
 
LRU_Replacement-Policy.pdf
LRU_Replacement-Policy.pdfLRU_Replacement-Policy.pdf
LRU_Replacement-Policy.pdf
 
Network Management Principles and Practice - 2nd Edition (2010)_2.pdf
Network Management Principles and Practice - 2nd Edition (2010)_2.pdfNetwork Management Principles and Practice - 2nd Edition (2010)_2.pdf
Network Management Principles and Practice - 2nd Edition (2010)_2.pdf
 
Euler Method Details
Euler Method Details Euler Method Details
Euler Method Details
 
Mini Project fo BE Engineering students
Mini Project fo BE Engineering  students  Mini Project fo BE Engineering  students
Mini Project fo BE Engineering students
 
Mini Project for Engineering Students BE or Btech Engineering students
Mini Project for Engineering Students BE or Btech Engineering students Mini Project for Engineering Students BE or Btech Engineering students
Mini Project for Engineering Students BE or Btech Engineering students
 
Ballistics Detsils
Ballistics Detsils Ballistics Detsils
Ballistics Detsils
 
VLSI Design_LAB MANUAL By Umakant Gohatre
VLSI Design_LAB MANUAL By Umakant GohatreVLSI Design_LAB MANUAL By Umakant Gohatre
VLSI Design_LAB MANUAL By Umakant Gohatre
 
Cryptography and Network Security
Cryptography and Network SecurityCryptography and Network Security
Cryptography and Network Security
 
cyber crime, Cyber Security, Introduction, Umakant Bhaskar Gohatre
cyber crime, Cyber Security, Introduction, Umakant Bhaskar Gohatre cyber crime, Cyber Security, Introduction, Umakant Bhaskar Gohatre
cyber crime, Cyber Security, Introduction, Umakant Bhaskar Gohatre
 
Image Compression, Introduction Data Compression/ Data compression, modelling...
Image Compression, Introduction Data Compression/ Data compression, modelling...Image Compression, Introduction Data Compression/ Data compression, modelling...
Image Compression, Introduction Data Compression/ Data compression, modelling...
 
Introduction Data Compression/ Data compression, modelling and coding,Image C...
Introduction Data Compression/ Data compression, modelling and coding,Image C...Introduction Data Compression/ Data compression, modelling and coding,Image C...
Introduction Data Compression/ Data compression, modelling and coding,Image C...
 
Python overview
Python overviewPython overview
Python overview
 
Python numbers
Python numbersPython numbers
Python numbers
 
Python networking
Python networkingPython networking
Python networking
 
Python multithreading
Python multithreadingPython multithreading
Python multithreading
 

Recently uploaded

杨洋李一桐做爱视频流出【网芷:ht28.co】国产国产午夜精华>>>[网趾:ht28.co】]<<<
杨洋李一桐做爱视频流出【网芷:ht28.co】国产国产午夜精华>>>[网趾:ht28.co】]<<<杨洋李一桐做爱视频流出【网芷:ht28.co】国产国产午夜精华>>>[网趾:ht28.co】]<<<
杨洋李一桐做爱视频流出【网芷:ht28.co】国产国产午夜精华>>>[网趾:ht28.co】]<<<
amzhoxvzidbke
 
Chapter 1 Introduction to Software Engineering and Process Models.pdf
Chapter 1 Introduction to Software Engineering and Process Models.pdfChapter 1 Introduction to Software Engineering and Process Models.pdf
Chapter 1 Introduction to Software Engineering and Process Models.pdf
MeghaGupta952452
 
Smart Factory – Starter Engagement Design.pptx
Smart Factory – Starter Engagement Design.pptxSmart Factory – Starter Engagement Design.pptx
Smart Factory – Starter Engagement Design.pptx
longngoai00
 
EAAP2023 : Durabilité et services écosystémiques de l'élevage ovin de montagne
EAAP2023 : Durabilité et services écosystémiques de l'élevage ovin de montagneEAAP2023 : Durabilité et services écosystémiques de l'élevage ovin de montagne
EAAP2023 : Durabilité et services écosystémiques de l'élevage ovin de montagne
idelewebmestre
 
charting the development of the autonomous train
charting the development of the autonomous traincharting the development of the autonomous train
charting the development of the autonomous train
huseindihon
 
FINE-TUNING OF SMALL/MEDIUM LLMS FOR BUSINESS QA ON STRUCTURED DATA
FINE-TUNING OF SMALL/MEDIUM LLMS FOR BUSINESS QA ON STRUCTURED DATAFINE-TUNING OF SMALL/MEDIUM LLMS FOR BUSINESS QA ON STRUCTURED DATA
FINE-TUNING OF SMALL/MEDIUM LLMS FOR BUSINESS QA ON STRUCTURED DATA
kevig
 
Introduction And Differences Between File System And Dbms.pptx
Introduction And Differences Between File System And Dbms.pptxIntroduction And Differences Between File System And Dbms.pptx
Introduction And Differences Between File System And Dbms.pptx
SerendipityYoon
 
If we're running two pumps, why aren't we getting twice as much flow? v.17
If we're running two pumps, why aren't we getting twice as much flow? v.17If we're running two pumps, why aren't we getting twice as much flow? v.17
If we're running two pumps, why aren't we getting twice as much flow? v.17
Brian Gongol
 
Girls Call Chennai 000XX00000 Provide Best And Top Girl Service And No1 in City
Girls Call Chennai 000XX00000 Provide Best And Top Girl Service And No1 in CityGirls Call Chennai 000XX00000 Provide Best And Top Girl Service And No1 in City
Girls Call Chennai 000XX00000 Provide Best And Top Girl Service And No1 in City
sunnuchadda
 
AI chapter1 introduction to artificial intelligence
AI chapter1 introduction to artificial intelligenceAI chapter1 introduction to artificial intelligence
AI chapter1 introduction to artificial intelligence
GeethaAL
 
LOCAL-BUDGET-CIRCULAR-NO-158-DATED-JULY-11-2024.pdf
LOCAL-BUDGET-CIRCULAR-NO-158-DATED-JULY-11-2024.pdfLOCAL-BUDGET-CIRCULAR-NO-158-DATED-JULY-11-2024.pdf
LOCAL-BUDGET-CIRCULAR-NO-158-DATED-JULY-11-2024.pdf
jellyjm
 
Red Hat Enterprise Linux Administration 9.0 RH124 pdf
Red Hat Enterprise Linux Administration 9.0 RH124 pdfRed Hat Enterprise Linux Administration 9.0 RH124 pdf
Red Hat Enterprise Linux Administration 9.0 RH124 pdf
mdfkobir
 
IE-469-Lecture-Notes-3IE-469-Lecture-Notes-3.pptx
IE-469-Lecture-Notes-3IE-469-Lecture-Notes-3.pptxIE-469-Lecture-Notes-3IE-469-Lecture-Notes-3.pptx
IE-469-Lecture-Notes-3IE-469-Lecture-Notes-3.pptx
BehairyAhmed2
 
AFCAT STATIC Genral knowledge important CAPSULE.pdf
AFCAT STATIC Genral knowledge important CAPSULE.pdfAFCAT STATIC Genral knowledge important CAPSULE.pdf
AFCAT STATIC Genral knowledge important CAPSULE.pdf
vibhapatil140
 
Hate speech detection using machine learning
Hate speech detection using machine learningHate speech detection using machine learning
Hate speech detection using machine learning
rakeshrocking3
 
OME754 – INDUSTRIAL SAFETY - unit notes.pptx
OME754 – INDUSTRIAL SAFETY - unit notes.pptxOME754 – INDUSTRIAL SAFETY - unit notes.pptx
OME754 – INDUSTRIAL SAFETY - unit notes.pptx
shanmugamram247
 
How to Formulate A Good Research Question
How to Formulate A  Good Research QuestionHow to Formulate A  Good Research Question
How to Formulate A Good Research Question
rkpv2002
 
Technical Seminar of Mca computer vision .ppt
Technical Seminar of Mca computer vision .pptTechnical Seminar of Mca computer vision .ppt
Technical Seminar of Mca computer vision .ppt
AnkitaVerma776806
 
1. DEE 1203 ELECTRICAL ENGINEERING DRAWING.pdf
1. DEE 1203 ELECTRICAL ENGINEERING DRAWING.pdf1. DEE 1203 ELECTRICAL ENGINEERING DRAWING.pdf
1. DEE 1203 ELECTRICAL ENGINEERING DRAWING.pdf
AsiimweJulius2
 
Disaster Management and Mitigation presentation
Disaster Management and Mitigation presentationDisaster Management and Mitigation presentation
Disaster Management and Mitigation presentation
RajaRamannaTarigoppu
 

Recently uploaded (20)

杨洋李一桐做爱视频流出【网芷:ht28.co】国产国产午夜精华>>>[网趾:ht28.co】]<<<
杨洋李一桐做爱视频流出【网芷:ht28.co】国产国产午夜精华>>>[网趾:ht28.co】]<<<杨洋李一桐做爱视频流出【网芷:ht28.co】国产国产午夜精华>>>[网趾:ht28.co】]<<<
杨洋李一桐做爱视频流出【网芷:ht28.co】国产国产午夜精华>>>[网趾:ht28.co】]<<<
 
Chapter 1 Introduction to Software Engineering and Process Models.pdf
Chapter 1 Introduction to Software Engineering and Process Models.pdfChapter 1 Introduction to Software Engineering and Process Models.pdf
Chapter 1 Introduction to Software Engineering and Process Models.pdf
 
Smart Factory – Starter Engagement Design.pptx
Smart Factory – Starter Engagement Design.pptxSmart Factory – Starter Engagement Design.pptx
Smart Factory – Starter Engagement Design.pptx
 
EAAP2023 : Durabilité et services écosystémiques de l'élevage ovin de montagne
EAAP2023 : Durabilité et services écosystémiques de l'élevage ovin de montagneEAAP2023 : Durabilité et services écosystémiques de l'élevage ovin de montagne
EAAP2023 : Durabilité et services écosystémiques de l'élevage ovin de montagne
 
charting the development of the autonomous train
charting the development of the autonomous traincharting the development of the autonomous train
charting the development of the autonomous train
 
FINE-TUNING OF SMALL/MEDIUM LLMS FOR BUSINESS QA ON STRUCTURED DATA
FINE-TUNING OF SMALL/MEDIUM LLMS FOR BUSINESS QA ON STRUCTURED DATAFINE-TUNING OF SMALL/MEDIUM LLMS FOR BUSINESS QA ON STRUCTURED DATA
FINE-TUNING OF SMALL/MEDIUM LLMS FOR BUSINESS QA ON STRUCTURED DATA
 
Introduction And Differences Between File System And Dbms.pptx
Introduction And Differences Between File System And Dbms.pptxIntroduction And Differences Between File System And Dbms.pptx
Introduction And Differences Between File System And Dbms.pptx
 
If we're running two pumps, why aren't we getting twice as much flow? v.17
If we're running two pumps, why aren't we getting twice as much flow? v.17If we're running two pumps, why aren't we getting twice as much flow? v.17
If we're running two pumps, why aren't we getting twice as much flow? v.17
 
Girls Call Chennai 000XX00000 Provide Best And Top Girl Service And No1 in City
Girls Call Chennai 000XX00000 Provide Best And Top Girl Service And No1 in CityGirls Call Chennai 000XX00000 Provide Best And Top Girl Service And No1 in City
Girls Call Chennai 000XX00000 Provide Best And Top Girl Service And No1 in City
 
AI chapter1 introduction to artificial intelligence
AI chapter1 introduction to artificial intelligenceAI chapter1 introduction to artificial intelligence
AI chapter1 introduction to artificial intelligence
 
LOCAL-BUDGET-CIRCULAR-NO-158-DATED-JULY-11-2024.pdf
LOCAL-BUDGET-CIRCULAR-NO-158-DATED-JULY-11-2024.pdfLOCAL-BUDGET-CIRCULAR-NO-158-DATED-JULY-11-2024.pdf
LOCAL-BUDGET-CIRCULAR-NO-158-DATED-JULY-11-2024.pdf
 
Red Hat Enterprise Linux Administration 9.0 RH124 pdf
Red Hat Enterprise Linux Administration 9.0 RH124 pdfRed Hat Enterprise Linux Administration 9.0 RH124 pdf
Red Hat Enterprise Linux Administration 9.0 RH124 pdf
 
IE-469-Lecture-Notes-3IE-469-Lecture-Notes-3.pptx
IE-469-Lecture-Notes-3IE-469-Lecture-Notes-3.pptxIE-469-Lecture-Notes-3IE-469-Lecture-Notes-3.pptx
IE-469-Lecture-Notes-3IE-469-Lecture-Notes-3.pptx
 
AFCAT STATIC Genral knowledge important CAPSULE.pdf
AFCAT STATIC Genral knowledge important CAPSULE.pdfAFCAT STATIC Genral knowledge important CAPSULE.pdf
AFCAT STATIC Genral knowledge important CAPSULE.pdf
 
Hate speech detection using machine learning
Hate speech detection using machine learningHate speech detection using machine learning
Hate speech detection using machine learning
 
OME754 – INDUSTRIAL SAFETY - unit notes.pptx
OME754 – INDUSTRIAL SAFETY - unit notes.pptxOME754 – INDUSTRIAL SAFETY - unit notes.pptx
OME754 – INDUSTRIAL SAFETY - unit notes.pptx
 
How to Formulate A Good Research Question
How to Formulate A  Good Research QuestionHow to Formulate A  Good Research Question
How to Formulate A Good Research Question
 
Technical Seminar of Mca computer vision .ppt
Technical Seminar of Mca computer vision .pptTechnical Seminar of Mca computer vision .ppt
Technical Seminar of Mca computer vision .ppt
 
1. DEE 1203 ELECTRICAL ENGINEERING DRAWING.pdf
1. DEE 1203 ELECTRICAL ENGINEERING DRAWING.pdf1. DEE 1203 ELECTRICAL ENGINEERING DRAWING.pdf
1. DEE 1203 ELECTRICAL ENGINEERING DRAWING.pdf
 
Disaster Management and Mitigation presentation
Disaster Management and Mitigation presentationDisaster Management and Mitigation presentation
Disaster Management and Mitigation presentation
 

Python database access

  • 1. http://www.tutorialspoint.com/python/python_database_access.htm Copyright © tutorialspoint.com PYTHON MYSQL DATABASE ACCESS The Pythonstandard for database interfaces is the PythonDB-API. Most Pythondatabase interfaces adhere to this standard. Youcanchoose the right database for your application. PythonDatabase API supports a wide range of database servers: GadFly mSQL MySQL PostgreSQL Microsoft SQL Server 2000 Informix Interbase Oracle Sybase Here is the list of available Pythondatabase interfaces: PythonDatabase Interfaces and APIs .Youmust download a separate DB API module for eachdatabase youneed to access. For example, if youneed to access anOracle database as wellas a MySQL database, youmust download boththe Oracle and the MySQL database modules. The DB API provides a minimalstandard for working withdatabases using Pythonstructures and syntax wherever possible. This API includes the following: Importing the API module. Acquiring a connectionwiththe database. Issuing SQL statements and stored procedures. Closing the connection We would learnallthe concepts using MySQL, so let's talk about MySQLdb module only. What is MySQLdb? MySQLdb is aninterface for connecting to a MySQL database server fromPython. It implements the Python Database API v2.0 and is built ontop of the MySQL C API. How do I install the MySQLdb? Before proceeding, youmake sure youhave MySQLdb installed onyour machine. Just type the following inyour Pythonscript and execute it: #!/usr/bin/python import MySQLdb If it produces the following result, thenit means MySQLdb module is not installed: Traceback (most recent call last): File "test.py", line 3, in <module>
  • 2. import MySQLdb ImportError: No module named MySQLdb To installMySQLdb module, download it fromMySQLdb 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 Note: Make sure youhave root privilege to installabove module. Database Connection: Before connecting to a MySQL database, make sure of the followings: Youhave created a database TESTDB. Youhave created a table EMPLOYEE inTESTDB. This table is having fields FIRST_NAME, LAST_NAME, AGE, SEX and INCOME. User ID "testuser" and password "test123" are set to access TESTDB. Pythonmodule MySQLdb is installed properly onyour machine. Youhave gone throughMySQL tutorialto understand MySQL Basics. Example: Following is the example of connecting withMySQL 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 inmy Linux machine. Database version : 5.0.45 If a connectionis established withthe datasource, thena ConnectionObject 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, whichinturnis used to execute SQL queries. Finally, before coming out, it ensures that database connectionis closed and resources are released. Creating Database Table: Once a database connectionis established, we are ready to create tables or records into the database tables
  • 3. using execute method of the created cursor. Example: First, let's create 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() INSERT Operation: INSERT operationis required whenyouwant to create your records into a database table. Example: Following is the example, whichexecutes SQL INSERT statement to create a record into 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() Above example canbe writtenas follows to create SQL queries dynamically:
  • 4. #!/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 ('%s', '%s', '%d', '%c', '%d' )" % ('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() Example: Following code segment is another formof executionwhere youcanpass parameters directly: .................................. user_id = "test123" password = "password" con.execute('insert into Login values("%s", "%s")' % (user_id, password)) .................................. READ Operation: READ Operationonany databasse means to fetchsome usefulinformationfromthe database. Once our database connectionis established, we are ready to make a query into this database. We canuse either fetchone() method to fetchsingle record or fetchall() method to fetechmultiple values froma database table. fetchone(): This method fetches the next row of a query result set. A result set is anobject that is returned whena cursor object is used to query a table. fetchall(): This method fetches allthe rows ina result set. If some rows have already beenextracted fromthe result set, the fetchall() method retrieves the remaining rows fromthe result set. rowcount: This is a read-only attribute and returns the number of rows that were affected by an execute() method. Example: Following is the procedure to query allthe records fromEMPLOYEE table having salary more than1000: #!/usr/bin/python import MySQLdb
  • 5. # 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 = "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 willproduce the following result: fname=Mac, lname=Mohan, age=20, sex=M, income=2000 Update Operation: UPDATE Operationonany databasse means to update one or more records, whichare already available inthe database. Following is the procedure to update allthe records having SEX as 'M'. Here, we willincrease AGE of allthe males by one year. Example: #!/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:
  • 6. DELETE operationis required whenyouwant to delete some records fromyour database. Following is the procedure to delete allthe records fromEMPLOYEE where AGE is more than20: Example: #!/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() Performing Transactions: Transactions are a mechanismthat ensures data consistency. Transactions should have the following four properties: Atomicity: Either a transactioncompletes or nothing happens at all. Consistency: A transactionmust start ina consistent state and leave the systemina consistent state. Isolation: Intermediate results of a transactionare not visible outside the current transaction. Durability: Once a transactionwas committed, the effects are persistent, evenafter a systemfailure. The PythonDB API 2.0 provides two methods to either commit or rollback a transaction. Example: Youalready have seenhow we have implemented transations. Here is againsimilar 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 Operation: Commit is the operation, whichgives a greensignalto database to finalize the changes, and after this operation, no change canbe reverted back. Here is a simple example to callcommit method. db.commit()
  • 7. ROLLBACK Operation: If youare not satisfied withone or more of the changes and youwant to revert back those changes completely, thenuse rollback() method. Here is a simple example to callrollback() method. db.rollback() Disconnecting Database: To disconnect Database connection, use close() method. db.close() If the connectionto a database is closed by the user withthe close() method, any outstanding transactions are rolled back by the DB. However, instead of depending onany of DB lower levelimplementationdetails, your applicationwould be better off calling commit or rollback explicitly. Handling Errors: There are many sources of errors. A few examples are a syntax error inanexecuted SQL statement, a connectionfailure, or calling the fetchmethod for analready canceled or finished statement handle. The DB API defines a number of errors that must exist ineachdatabase module. The following table lists these exceptions. Exception Description Warning Used for non-fatalissues. Must subclass StandardError. Error Base class for errors. Must subclass StandardError. InterfaceError Used for errors inthe database module, not the database itself. Must subclass Error. DatabaseError Used for errors inthe database. Must subclass Error. DataError Subclass of DatabaseError that refers to errors inthe data. OperationalError Subclass of DatabaseError that refers to errors suchas the loss of a connectionto the database. These errors are generally outside of the controlof the Pythonscripter. IntegrityError Subclass of DatabaseError for situations that would damage the relationalintegrity, suchas uniqueness constraints or foreignkeys. InternalError Subclass of DatabaseError that refers to errors internalto the database module, such as a cursor no longer being active. ProgrammingError Subclass of DatabaseError that refers to errors suchas a bad table name and other things that cansafely be blamed onyou. NotSupportedError Subclass of DatabaseError that refers to trying to callunsupported functionality. Your Pythonscripts should handle these errors, but before using any of the above exceptions, make sure your MySQLdb has support for that exception. Youcanget more informationabout themby reading the DB API 2.0 specification.