Top Banner
14
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Database connectivity in python
Page 2: Database connectivity in python

Date:20/02/2015

[email protected]

sanooja jabbar t.com/baabtra

twitter.com/baabtra

in.linkedin.com/in/baabtra

Database Connectivity

in

Page 3: Database connectivity in python

Database Connectivity

❏ Python Database API supports a wide range of database

servers:

- GadFly

- mySQL

- MySQL

- PostgreSQL

- Microsoft SQL Server

- Informix

- Interbase

- Oracle

- Sybase

Page 4: Database connectivity in python

Step1: Database import

❏ Import modules for database in your python program

- MySQL

- PostgreSQL

import MySQLdb

import psycopg2

Page 5: Database connectivity in python

Step1: Database import

❏ Import modules for database in your python program

- MySQL

- PostgreSQL

import MySQLdb

import psycopg2

Traceback (most recent call last):

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

import MySQLdb

ImportError: No module named

MySQLdb

Error

If the above error happens that means you have

not installed the mysql/postgresql module for the

python version you are using

Solution : download it from

http://sourceforge.net/projects/mysql-python

Page 6: Database connectivity in python

Step 2 – Establishing connection

❏ Open a database connection with your program using connect()

– Mysql

– PostgreSql

db = MySQLdb.connect(user=‘root', password=‘root',

host=‘localhost', database=‘pydb' )

db = psycopg2.connect(user=‘root', password=‘root',

host=‘localhost', database=‘pydb' )

Page 7: Database connectivity in python

Step 2 – Establishing connection

❏ Open database connection

– Mysql

– PostgreSql

db = MySQLdb.connect(user=‘root', password=‘root', host=‘localhost',

database=‘pydb )

db = psycopg2.connect(user=‘root', password=‘root', host=‘localhost',

database=‘pydb' )

the connect() constructor creates a connection to the MySQL server and returns a MySQLConnection object

Page 8: Database connectivity in python

Step 3 – Creating cursor object

❏ We need to create the object of a class called cursor that allows

Python code to execute database command in a database session.

❏ Cursors are created by the connection.cursor() method: they are

bound to the connection for the entire lifetime and all the commands

are executed in the context of the database session wrapped by the

connection.

❏ We can close the connection manually using connection.close()

❏ Mysql / PostgreSql

cursor = db.cursor()

Page 9: Database connectivity in python

Step 4 -Execute SQL query

We can execute the sql queries from python program using execute() method

associated with cursor object . Examples

- cursor.execute(“select * from tbl_login”)

- cursor.execute(“select vchr_login_name from tbl_login

where pk_int_login_id=%s”, x)

- cursor.execute("select a from tbl where b=%s and c=%s", (x, y))

Page 10: Database connectivity in python

Step 4 -Execute SQL query

❏ Executes an SQL command against all parameter sequences or

mappings found in the sequence sql

- cursor.execute("insert into tbl_login

(vchr_login_name,vchr_pwd)

values(‘admin’ , ’admin123’)”)

db.commit();

- cursor.executemany("insert into tbl_login

(vchr_login_name,vchr_pwd)

values(‘admin’ , ’admin123’),(‘raj’,’raj123’)”)

db.commit();

Page 11: Database connectivity in python

Step 5 – Fetch data from database

❏ MySQLdb provides multiple ways to retrieve data such as:

– fetchall()

• Fetch all (remaining) rows of a query result, returning them as

a sequence of sequences (e.g. a list of tuples).

– fetchmany(size)

• Fetch the next set of rows of a query result, returning a

sequence of sequences (e.g. a list of tuples) .It will return

number of rows that matches to the size argument

– fetchone()

• Fetch the next row of a query result set, returning a single

sequence, or None when no more data is available

Page 12: Database connectivity in python

Example

import MySQLdb

def insertEmp(str_name,str_pwd):

db=MySQLdb.connect( 'localhost' ,' root' , ' ' , 'pydb' )

cursor=db.cursor()

cursor.execute("insert into tbl_login (vchr_login_name,vchr_pwd)

values(%s,%s);",(str_name,str_pwd))

db.commit()

cursor.execute("select * from tbl_login")

result=cursor.fetchall()

db.close()

print "loginid\tname\tpassword"

for row in result:

login=row[0]

name=row[1]

password=row[2]

print "%d\t%s\t%s"%(login,name,password)

str_name=raw_input("enter user name : ")

str_pwd=raw_input("Enter password : ")

insertEmp(str_name,str_pwd)

Page 13: Database connectivity in python
Page 14: Database connectivity in python