Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

Monday, July 31, 2023

PYTHON MY SQL DATA BASE ACCESS

 

PYTHON MY SQL DATA BASE ACCESS

 

*                      Gad fly

*                      msql

*                      my sql

*                      postgre sql

*                      microsoft sql server 2000

*                      informix

*                      interbase

*                      oracle

*                      sybase

WHAT IS MY SQL?

        My sql is an interface for connecting to a my sql data base 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 MY SQLDB?

#!/usr/bin/python

import MySQLdb

traceback (most recent call last):

 file"test.py",line 3,in <module>
   import Mysqldb

importerror:no module named My SQLdb

 

for Ubuntu,use the folllowing command -

$sudo apt get install python pip pythin dev libmysqlclient dev

for fedora , use the following command

 $sudo dnf install python python devel mysql redhat rpm config gcc 

for python command prompt use the following command

pip install MySQL-python

 

DATABASE CONNECTION

#!/usr/bin/python

 

import Mysqldb

 

#open database connection

db=My SQLdb.connect("127.0.0.1""sample""linkme30""SAMPLEDATA")

 

#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

import MySQLdb

#open database connection

db=MySQLdb.db.connect("127.0.0.1","SAMPLE","linkme30","sample data")

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

#create table as per requirement

sql="""create table jkemployee(

      empno int NOT NULL,

      empname  char(20),

      job char(20),

      age int,

      sex char(1),

      salary float )"""

 

cursor.execute(sql)

#disconnect from server

db.close()

INSERT operation

import MySQLdb

db = MSQLdb.connect("127.0.0.1","SAMPLE',"linkMe30","

SAMPLEDATA")

cursor=db.cursor()

sql="""INSERT INTO                  JKEMPLOYEE(empno,empname,job,age,sex,salary)          VALUES(100, 'mohan', 'manager', 25,'M' 18000)"""

 

try:

   #Execute the SQL command

   cursor.execuet(sql)

    #commit your changes in the database

    db.commit()

 

except:

     #rollback in case there is any error

     db.rollback()

# disconnect from server

db.close()

 

#!/usr/bin/python

import MySQLdb

#open database connection

db= MySQLdb.connec("127.0.0.1","SAMPLE","linkme30","SAMPLEDATA”)

#prepare a cursor object using cursor() method

cursor = db.cursor()

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

sql = "INSERT INTO jkemployee(empno,empname,job,age,sex,salary)

          VALUES('%d','%s','%s','%d','%c','%f')"%\

         (102, 'mohan','clerk',26,'M',12000)

try:

    cursor.execute(sql)  #Execute the SQL command

fb.commit()                  #commit your changes in the database

 

except:

   db.rollback()     #rollback in case there is any error

#disconnect from server

db.close

Example

following code segment is another form of ececution where you can pass parameters directly?

...........................................

user id = "SAMPLE"

password = "LinkMe30"

 

con.execute('insert into login values("%s","%s")'%\

                     (user_id, password))

 

READ Operation

import MySQLdb

#open database connection

db=MySQldb.connect("127.0.01","SAMPLE","LinkMe30","SAMPLEDATA")

#prepare a cursor object using cursor() method

cursor=db.cursor()

sql="SELECT*FROM JKEMPLOyee
          WHERE SALARY>'%d'"%10000)

try:

   #execute the SQL command

    cursor.execute(sql)

     #fetch all the rows in a list of lists.

   results=cursor.fetchall()

   for row in results:

          empno=row[0]

           empname= row[1]

          job= row[2]

         age= row[3]

         sex= row[4]

         salary= row[5]

       #now print fetched result

                           print "employee no=%d,employee name=%s, designation=%s,age=%d,sex=%c,salary=%f"% \

                       (empno,empname,job,sex,salary)

except:

       print ("error: unable to fetch data")

#disconnect from server

fb.close()

Output

employee no=100, employee  name=ramesh, designation=manager, age=26, sex=M,income=18000

update operation

import MySQLdb

#open database connection

db= MySQLdb.connect("127.0.0.1","SAMPLE","linkMe30","SAMPLEDATA")

#prepare cursor object using cursor() method

cursor = db.cursor()

#prepare a cursor object using cursor() method

 

cursor=db.cursor()

#prepare SQL query to UPDATE required records

sql ="UPDATE JKEMPLOYEE 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

example

#!/usr/bin/python

 

import MySQLdb

 

#open database connection

db=MySQLdb.connect("127.0.0.1","SAMPLE" ,"linkMe30","SAMPLEDATA")

#prepare a cursor object using cursor() method

cursor=db.cursor()

#prepare a cursor object using cursor() method

cursor=db.cursor()

#prepare SQL query to DELETE required records

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

 

 

Sunday, June 25, 2023

Image processing in python with pillow

           Image processing in python with pillow

Note:

pillow <2.0.0 suports python versions 2.4,2.5,2.6,2.7

pillow >=2.0.0 supports python versions 2.6,2.7,3.2,3.3,3.4,3.5

BASIC INSTALLATION

installations require building from source as detailed below.

Installation pillow with pip:

$pip install pillow

Introduction

 Modes:

mode

bands

description

"l"

1

black and white (monochrome ),one bit per pixel

"L"

1

gray scale ,one 8-bit byte per pixel

"p"

1

palette encoding :one byte per pixel ,with a palette of class Image palette translating the pixels to colors . this mode is experimental ;refer to the online documentation  

"RHB"

3

true red green blue color ,three bytes per pixel

"RGBA"

4

true color with a transparency band ,four bytes per pixel ,with the A channel varying from 0 to 255 for opaque

"CMYK"

4

cyan magenta yellow black color four bytes per pixel

"YCbCr"

3

color video format , three 8-bit pixels

"I"

1

32-bit  integer pixels

"F"

1

32-bit float pixels

 

Sizes

(width,height)

Coordinates:

(x,y,z)

Open function:

image. open (file)

image.open(file,mode)

 

from PIL import Image

imgvar =Image.open(r"D:\Python27\Lib\site-packages\PIL\flo.jpg")

imgvar.show()

Output









Changing Image type

from PIL import Image

imgvar=Image.open(r"D:\Python27\Lib\site-packages\PIL\flo.jpg")

imgvar.save('new_dog_image.png')

Image name: new_dog_image.png

Resizing images

from PIL import image

imgvar=Image.open(r"D:\Python27\Lib\site-packages\PIL\flo.jpg")

new_imgvar=Image.resize((300,300))

new_imgvar.save('new_300_dog_image.jpg')

print("\n Original image size:",img_var.size)

print("\n resized image size:",imgvar.size)

Output

original image size:(300,168)

resized image size:(150,100)

original image size:(300,168)

Resizing images(thumbnail())

from PIL import image

imgvar=Image.open(r"D:\Python27\Lib\site-packages\PIL\flo.jpg")

imgvar.thumbnail((150,100))

imgavr.save('new_dog_image1.jpg')

print(imgvar.size)

imgvar.show()

OUTPUT

aspect ratio new size(150,84)



 

 

 Example for filter option

from PIL import Image

imgvar = Image.open(r'E:\Lib\site-packages\PIL\BIRD.jpg')

imgvar.thumbnail((120,50),image.NEAREST)

imgvar.save('new_dog_image1.jpg')

print(imgvar.size)

imgvar.show()

Output

the size of the picture is (89,50)

 

ROTATING IMAGE

 

from PIL import Image

im=image.open(r'E:\Lib\site-packages\PIL\BIRD.jpg')

im.rotate(45).show()

 

OUTPUT











this example image dog_image.jpg file rotate 45 degree

 

DRAWING IMAGE

 

from PIL import image

img=image.new("RGB",(100,250),"red")

img.show()

 

OUTPUT



 

 

 

 


INTERPOLATING TO IMAGES USING BLEND()

 

Image.blend(image1,image2,alpha)

 

from PIL import Image

img1=image.open('new_dog_image14.jpg')

img2=image.open('new_cat_image.jpg')

img_blend=Image.blend(img1,img2,0.0)

img_blend.show()

 

 

COLOR TRANSFORM

 

#convert RGB to gray scale mode

from PIL import Image

img1=Image.open(r'E:\Lib\site-packages\PIL\BIRD.jpg')

img1.convert("L").show()

Output











CROPPING IMAGE FILES

 

#convert RBG to gray scale mode

 

from PIL import Image

img1=Image.open(r'E:\Lib\site-packages\PIL\BIRD.jpg')

crop_image=img1.crop(100,100,150,150)

crop_image.save("cropped_dog_image.jpg")

crop_image.show()

Output





FILTER AN IMAGE FILES

 

FILTERS

v BLUR

v CONTOUR

v DETAIL

v EDGE_ENHANCE

v EDGE_ENHANCE_MORE

v EMBOSS

v FIND_EDGES

v SMOOTH

v SMOOTH_MORE

v SHARPEN

 

from PIL import ImageFilter

from PIL import Image

#filter to enhance the picture to emboss

img1=Image.open(r'E:\Lib\site-packages\PIL\BIRD.jpg')

img1.filter(ImageFilter.EMBOSS).show()

Output



















FLIPPING IMAGES

from PIL import Image

imgvar=Image.open(r'E:\Lib\site-packages\PIL\BIRD.jpg')

imgvar.show()

img_flip=imgvar.transpose(Image.FLIP_LEFT_RIGHT)

img_flip.show()

Output


















from PIL import Image

#find the size of the image

img1=Image.open(r'E:\Lib\site-packages\PIL\LILY.jpg')

img1.rotate(45).save("xyz.png")

img1.show()

img1.convert("L").save("jkpwimg1.jpg")

img2=Image.open("jkpwimg1.jpg")

img2.show()

img3=Image.open("xyz.png")

img3.show()

Output













PASTING AN IMAGE ON TO ANOTHER IMAGE

#an image pasted on the another image on the right bottom

from PIL import Image

img1=Image.open(r'E:\Lib\site-packages\PIL\p1.jpg')

img2=Image.open(r'E:\Lib\site-packages\PIL\p2.jpg')

image_copy=img1.copy()

position=((image_copy.width-img2.width-350),(image_copy.height-img2.height-250))

image_copy.paste(img2,position)

image_copy.save('pasted_image.jpg')

image_copy.show()

  

Output

img1


img2