SlideShare una empresa de Scribd logo
1 de 28
CONNECT TO POSTGRESQL
With python script
 psycopg is a PostgreSQL database adapter for
the Python_ programming language. This is
version 2, a complete rewrite of the original
code to provide new-style classes for
connection and cursor objects and other sweet
candies.
 Homepage:
http://initd.org/projects/psycopg2
PyGreSQL – PostgreSQL module for Python
PyGreSQL is an open-source Python module
that interfaces to a PostgreSQL database. It
embeds the PostgreSQL query library to allow
easy use of the powerful PostgreSQL features
from a Python script.
Python version 2.5 or 2.6 or 2.7
PostGreSQL 9.1 or higher
Linux
Look for a package such as python-psycopg2
sudo apt-get install python-psycopg2 - to install
the package with all its dependencies.
Windows
 http://www.stickpeople.com/projects/python/win-psycopg/
 http://initd.org/psycopg/
 Binary(...) Binary(buffer) -> new binary object
Build an object capable to hold a binary string value.
 Date(...) - Date(year, month, day) -> new date
Build an object holding a date value.
 Time(...) - Time(hour, minutes, seconds, tzinfo=None) –> new time
Build an object holding a time value.
 Timestamp(...) -
Timestamp(year, month, day, hour, minutes, seconds, tzinfo=None) -
> new timestamp
Build an object holding a timestamp value
 Create a new database connection and returns a new connection instance.

connect(dsn=None, database=None, user=None, password=None, host=No
ne, port=None, connection_factory=None, cursor_factory=None, async=Fal
se).
 Parameters:
 Using the *connection_factory* parameter a different class or connections
factory can be specified. It should be a callable object taking a dsn
argument.
 Using the *cursor_factory* parameter, a new default cursor factory will be
used by cursor().
 Using *async*=True an asynchronous connection will be created.
 It allows to:
 create new cursors using the cursor() method to execute
database commands and queries,
 commit() - The changes are committed to the database.
 rollback() In case of an error, we roll back any possible
changes to our database table.
 The class cursor allows interaction with the database:
 send commands to the database using methods such as execute() and
executemany(),
 retrieve data from the database by iteration or using methods such as
fetchone(), fetchmany(), fetchall().
 cur.description – to get metadata
 copy-to – to copy db tables to a file
 copy-from – to copy files to a db
 scrollable()
 mogrify()
import psycopg2
Connect to an existing database
 conn=psycopg2.connect("dbname=test user=postgres")
- as a libpq connection string
 conn=psycopg2.connect(database=“test” user=“postgres")
- as a set of keyword arguments
Open a cursor to perform database operations
cur = conn.cursor()
 Psycopg cursor usually fetches all the record from database
during a query, usually which is a large dataset to be handled
in the client side, hence to do controlled transfer of data to the
client,we use server side cursors.
 Psycopg wraps the database server side cursor in named
cursors. A named cursor is created using the cursor() method
specifying the name parameter.
 To move in the dataset we use scroll() method and scrollable()
method to move backward as well
Make the changes to the database persistent
conn.commit()
Close communication with the database
cur.close()
conn.close()
connect_test.py
check_version.py
Form.py
CRUD
 cur.execute("DROP TABLE IF EXISTS tablename")
 cur.execute("CREATE TABLE tablename (id serial
PRIMARY KEY, num integer, data varchar)“)
 cur.executemany() ???????
Create and drop table
cur.execute("SELECT * FROM tablename")
cur.execute("INSERT INTO tablename
(num, data) VALUES (%s, %s)", ...
(100, “apple"))
insert
insertmany
Obtain data as Python objects
cur.fetchone(),cur.fetchall(),cur.fetchmany(5)
fetchone
fetchall
 Always be a %s, even if a different placeholder (such as a %d for
integers or %f for floats) may look more appropriate:
cur.execute("INSERT INTO tablename VALUES (%d)", (42,)) # WRONG
cur.execute("INSERT INTO tablenameVALUES (%s)", (42,)) # correct
 Named arguments are supported too using %(name)s placeholders.
cur.execute( """INSERT INTO tablename (an_int, a_date,
another_date, a_string) VALUES (%(int)s, %(date)s, %(date)s,
%(str)s);""", {'int': 10, 'str': "O'Reilly", 'date': datetime.date(2005,
11, 18)})
 The Python string operator % is not used: the execute() method accepts a
tuple or dictionary of values as second parameter.
 For positional variables binding, the second argument must always be a
sequence, even if it contains a single variable:
 cur.execute("INSERT INTO foo VALUES (%s)", "bar") # WRONG
 cur.execute("INSERT INTO foo VALUES (%s)", ("bar")) # WRONG
 cur.execute("INSERT INTO foo VALUES (%s)", ("bar",)) # correct
 cur.execute("INSERT INTO foo VALUES (%s)", ["bar"]) # correct
Python PostgreSQL
None NULL
Bool Bool
Float Real,double
Int,long Smallint,integer,bigint
Decimal Numeric
Str Varchar
Date Date
Datetime Timestamp
List array
Many standard Python types are adapted into SQL and returned as Python objects
when a query is executed.
Psycopg casts Python variables to SQL literals by type.
cur.execute("UPDATE tablename SET
price=50000 WHERE id1")
update
delete
cur.execute("UPDATE tablename SET
price=%s WHERE id=%s", (60000, 1))
cur.execute("SELECT * FROM tablename
WHERE id=%(id)s", {'id': 4 } )
Python Filescopy_from_db.py
Python Filescopy_to_db.py
Matadata.py
Information on db
autocommit
Writing image to db
Reading image from db
Python Filesdictionary_cursor.py
Psycopg2 - Connect to PostgreSQL using Python Script

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

Handling inline assembly in Clang and LLVM
Handling inline assembly in Clang and LLVMHandling inline assembly in Clang and LLVM
Handling inline assembly in Clang and LLVM
 
Sorting algorithms
Sorting algorithmsSorting algorithms
Sorting algorithms
 
Infix prefix postfix
Infix prefix postfixInfix prefix postfix
Infix prefix postfix
 
Lecture optimal binary search tree
Lecture optimal binary search tree Lecture optimal binary search tree
Lecture optimal binary search tree
 
Rust vs C++
Rust vs C++Rust vs C++
Rust vs C++
 
Insertion and merge sort
Insertion and merge sortInsertion and merge sort
Insertion and merge sort
 
Python Advanced – Building on the foundation
Python Advanced – Building on the foundationPython Advanced – Building on the foundation
Python Advanced – Building on the foundation
 
Numpy Talk at SIAM
Numpy Talk at SIAMNumpy Talk at SIAM
Numpy Talk at SIAM
 
Sets in python
Sets in pythonSets in python
Sets in python
 
Functional Programming in Swift
Functional Programming in SwiftFunctional Programming in Swift
Functional Programming in Swift
 
Functional Programming 101 with Scala and ZIO @FunctionalWorld
Functional Programming 101 with Scala and ZIO @FunctionalWorldFunctional Programming 101 with Scala and ZIO @FunctionalWorld
Functional Programming 101 with Scala and ZIO @FunctionalWorld
 
Quick Sort
Quick SortQuick Sort
Quick Sort
 
Data Structures- Part5 recursion
Data Structures- Part5 recursionData Structures- Part5 recursion
Data Structures- Part5 recursion
 
Algorithms with-java-advanced-1.0
Algorithms with-java-advanced-1.0Algorithms with-java-advanced-1.0
Algorithms with-java-advanced-1.0
 
Data Structures- Hashing
Data Structures- Hashing Data Structures- Hashing
Data Structures- Hashing
 
Introduction to NumPy
Introduction to NumPyIntroduction to NumPy
Introduction to NumPy
 
Stacks
StacksStacks
Stacks
 
Unit 4 queue
Unit   4 queueUnit   4 queue
Unit 4 queue
 
Python Dictionaries and Sets
Python Dictionaries and SetsPython Dictionaries and Sets
Python Dictionaries and Sets
 
Counting Sort
Counting SortCounting Sort
Counting Sort
 

Similar a Psycopg2 - Connect to PostgreSQL using Python Script

Hadoop Integration in Cassandra
Hadoop Integration in CassandraHadoop Integration in Cassandra
Hadoop Integration in CassandraJairam Chandar
 
Cascading Through Hadoop for the Boulder JUG
Cascading Through Hadoop for the Boulder JUGCascading Through Hadoop for the Boulder JUG
Cascading Through Hadoop for the Boulder JUGMatthew McCullough
 
Psycopg2 postgres python DDL Operaytions (select , Insert , update, create ta...
Psycopg2 postgres python DDL Operaytions (select , Insert , update, create ta...Psycopg2 postgres python DDL Operaytions (select , Insert , update, create ta...
Psycopg2 postgres python DDL Operaytions (select , Insert , update, create ta...sachin kumar
 
Introduction to Scalding and Monoids
Introduction to Scalding and MonoidsIntroduction to Scalding and Monoids
Introduction to Scalding and MonoidsHugo Gävert
 
Phil Bartie QGIS PLPython
Phil Bartie QGIS PLPythonPhil Bartie QGIS PLPython
Phil Bartie QGIS PLPythonRoss McDonald
 
Python postgre sql a wonderful wedding
Python postgre sql   a wonderful weddingPython postgre sql   a wonderful wedding
Python postgre sql a wonderful weddingStéphane Wirtel
 
Introduction to source{d} Engine and source{d} Lookout
Introduction to source{d} Engine and source{d} Lookout Introduction to source{d} Engine and source{d} Lookout
Introduction to source{d} Engine and source{d} Lookout source{d}
 
Modern technologies in data science
Modern technologies in data science Modern technologies in data science
Modern technologies in data science Chucheng Hsieh
 
Connecting and using PostgreSQL database with psycopg2 [Python 2.7]
Connecting and using PostgreSQL database with psycopg2 [Python 2.7]Connecting and using PostgreSQL database with psycopg2 [Python 2.7]
Connecting and using PostgreSQL database with psycopg2 [Python 2.7]Dinesh Neupane
 
Advance Map reduce - Apache hadoop Bigdata training by Design Pathshala
Advance Map reduce - Apache hadoop Bigdata training by Design PathshalaAdvance Map reduce - Apache hadoop Bigdata training by Design Pathshala
Advance Map reduce - Apache hadoop Bigdata training by Design PathshalaDesing Pathshala
 
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 CassandraDeependra Ariyadewa
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with ClojureDmitry Buzdin
 
Twitter Author Prediction from Tweets using Bayesian Network
Twitter Author Prediction from Tweets using Bayesian NetworkTwitter Author Prediction from Tweets using Bayesian Network
Twitter Author Prediction from Tweets using Bayesian NetworkHendy Irawan
 
Wprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
Wprowadzenie do technologii Big Data / Intro to Big Data EcosystemWprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
Wprowadzenie do technologii Big Data / Intro to Big Data EcosystemSages
 
Workshop presentation hands on r programming
Workshop presentation hands on r programmingWorkshop presentation hands on r programming
Workshop presentation hands on r programmingNimrita Koul
 
Hadoop_Pennonsoft
Hadoop_PennonsoftHadoop_Pennonsoft
Hadoop_PennonsoftPennonSoft
 

Similar a Psycopg2 - Connect to PostgreSQL using Python Script (20)

Hadoop Integration in Cassandra
Hadoop Integration in CassandraHadoop Integration in Cassandra
Hadoop Integration in Cassandra
 
Cascading Through Hadoop for the Boulder JUG
Cascading Through Hadoop for the Boulder JUGCascading Through Hadoop for the Boulder JUG
Cascading Through Hadoop for the Boulder JUG
 
Psycopg2 postgres python DDL Operaytions (select , Insert , update, create ta...
Psycopg2 postgres python DDL Operaytions (select , Insert , update, create ta...Psycopg2 postgres python DDL Operaytions (select , Insert , update, create ta...
Psycopg2 postgres python DDL Operaytions (select , Insert , update, create ta...
 
Spark_Documentation_Template1
Spark_Documentation_Template1Spark_Documentation_Template1
Spark_Documentation_Template1
 
Introduction to Scalding and Monoids
Introduction to Scalding and MonoidsIntroduction to Scalding and Monoids
Introduction to Scalding and Monoids
 
Phil Bartie QGIS PLPython
Phil Bartie QGIS PLPythonPhil Bartie QGIS PLPython
Phil Bartie QGIS PLPython
 
Python postgre sql a wonderful wedding
Python postgre sql   a wonderful weddingPython postgre sql   a wonderful wedding
Python postgre sql a wonderful wedding
 
Introduction to source{d} Engine and source{d} Lookout
Introduction to source{d} Engine and source{d} Lookout Introduction to source{d} Engine and source{d} Lookout
Introduction to source{d} Engine and source{d} Lookout
 
Modern technologies in data science
Modern technologies in data science Modern technologies in data science
Modern technologies in data science
 
Connecting and using PostgreSQL database with psycopg2 [Python 2.7]
Connecting and using PostgreSQL database with psycopg2 [Python 2.7]Connecting and using PostgreSQL database with psycopg2 [Python 2.7]
Connecting and using PostgreSQL database with psycopg2 [Python 2.7]
 
What is new in Java 8
What is new in Java 8What is new in Java 8
What is new in Java 8
 
Advance Map reduce - Apache hadoop Bigdata training by Design Pathshala
Advance Map reduce - Apache hadoop Bigdata training by Design PathshalaAdvance Map reduce - Apache hadoop Bigdata training by Design Pathshala
Advance Map reduce - Apache hadoop Bigdata training by Design Pathshala
 
Python database connection
Python database connectionPython database connection
Python database connection
 
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
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
Twitter Author Prediction from Tweets using Bayesian Network
Twitter Author Prediction from Tweets using Bayesian NetworkTwitter Author Prediction from Tweets using Bayesian Network
Twitter Author Prediction from Tweets using Bayesian Network
 
Wprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
Wprowadzenie do technologii Big Data / Intro to Big Data EcosystemWprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
Wprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
 
Workshop presentation hands on r programming
Workshop presentation hands on r programmingWorkshop presentation hands on r programming
Workshop presentation hands on r programming
 
Hadoop_Pennonsoft
Hadoop_PennonsoftHadoop_Pennonsoft
Hadoop_Pennonsoft
 
Database connectivity in python
Database connectivity in pythonDatabase connectivity in python
Database connectivity in python
 

Último

1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdfAldoGarca30
 
kiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal loadkiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal loadhamedmustafa094
 
Computer Networks Basics of Network Devices
Computer Networks  Basics of Network DevicesComputer Networks  Basics of Network Devices
Computer Networks Basics of Network DevicesChandrakantDivate1
 
Online electricity billing project report..pdf
Online electricity billing project report..pdfOnline electricity billing project report..pdf
Online electricity billing project report..pdfKamal Acharya
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VDineshKumar4165
 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startQuintin Balsdon
 
DC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationDC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationBhangaleSonal
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfJiananWang21
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayEpec Engineered Technologies
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXssuser89054b
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . pptDineshKumar4165
 
Online food ordering system project report.pdf
Online food ordering system project report.pdfOnline food ordering system project report.pdf
Online food ordering system project report.pdfKamal Acharya
 
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptxHOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptxSCMS School of Architecture
 
Wadi Rum luxhotel lodge Analysis case study.pptx
Wadi Rum luxhotel lodge Analysis case study.pptxWadi Rum luxhotel lodge Analysis case study.pptx
Wadi Rum luxhotel lodge Analysis case study.pptxNadaHaitham1
 
PE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and propertiesPE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and propertiessarkmank1
 
Hospital management system project report.pdf
Hospital management system project report.pdfHospital management system project report.pdf
Hospital management system project report.pdfKamal Acharya
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaOmar Fathy
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.Kamal Acharya
 

Último (20)

1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
 
kiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal loadkiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal load
 
Computer Networks Basics of Network Devices
Computer Networks  Basics of Network DevicesComputer Networks  Basics of Network Devices
Computer Networks Basics of Network Devices
 
Online electricity billing project report..pdf
Online electricity billing project report..pdfOnline electricity billing project report..pdf
Online electricity billing project report..pdf
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the start
 
DC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationDC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equation
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
Integrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - NeometrixIntegrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - Neometrix
 
Online food ordering system project report.pdf
Online food ordering system project report.pdfOnline food ordering system project report.pdf
Online food ordering system project report.pdf
 
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptxHOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
 
Wadi Rum luxhotel lodge Analysis case study.pptx
Wadi Rum luxhotel lodge Analysis case study.pptxWadi Rum luxhotel lodge Analysis case study.pptx
Wadi Rum luxhotel lodge Analysis case study.pptx
 
PE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and propertiesPE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and properties
 
Hospital management system project report.pdf
Hospital management system project report.pdfHospital management system project report.pdf
Hospital management system project report.pdf
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS Lambda
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.
 

Psycopg2 - Connect to PostgreSQL using Python Script

  • 2.  psycopg is a PostgreSQL database adapter for the Python_ programming language. This is version 2, a complete rewrite of the original code to provide new-style classes for connection and cursor objects and other sweet candies.  Homepage: http://initd.org/projects/psycopg2
  • 3. PyGreSQL – PostgreSQL module for Python PyGreSQL is an open-source Python module that interfaces to a PostgreSQL database. It embeds the PostgreSQL query library to allow easy use of the powerful PostgreSQL features from a Python script.
  • 4. Python version 2.5 or 2.6 or 2.7 PostGreSQL 9.1 or higher
  • 5. Linux Look for a package such as python-psycopg2 sudo apt-get install python-psycopg2 - to install the package with all its dependencies. Windows  http://www.stickpeople.com/projects/python/win-psycopg/  http://initd.org/psycopg/
  • 6.  Binary(...) Binary(buffer) -> new binary object Build an object capable to hold a binary string value.  Date(...) - Date(year, month, day) -> new date Build an object holding a date value.  Time(...) - Time(hour, minutes, seconds, tzinfo=None) –> new time Build an object holding a time value.  Timestamp(...) - Timestamp(year, month, day, hour, minutes, seconds, tzinfo=None) - > new timestamp Build an object holding a timestamp value
  • 7.  Create a new database connection and returns a new connection instance.  connect(dsn=None, database=None, user=None, password=None, host=No ne, port=None, connection_factory=None, cursor_factory=None, async=Fal se).  Parameters:  Using the *connection_factory* parameter a different class or connections factory can be specified. It should be a callable object taking a dsn argument.  Using the *cursor_factory* parameter, a new default cursor factory will be used by cursor().  Using *async*=True an asynchronous connection will be created.
  • 8.  It allows to:  create new cursors using the cursor() method to execute database commands and queries,  commit() - The changes are committed to the database.  rollback() In case of an error, we roll back any possible changes to our database table.
  • 9.  The class cursor allows interaction with the database:  send commands to the database using methods such as execute() and executemany(),  retrieve data from the database by iteration or using methods such as fetchone(), fetchmany(), fetchall().  cur.description – to get metadata  copy-to – to copy db tables to a file  copy-from – to copy files to a db  scrollable()  mogrify()
  • 10. import psycopg2 Connect to an existing database  conn=psycopg2.connect("dbname=test user=postgres") - as a libpq connection string  conn=psycopg2.connect(database=“test” user=“postgres") - as a set of keyword arguments Open a cursor to perform database operations cur = conn.cursor()
  • 11.  Psycopg cursor usually fetches all the record from database during a query, usually which is a large dataset to be handled in the client side, hence to do controlled transfer of data to the client,we use server side cursors.  Psycopg wraps the database server side cursor in named cursors. A named cursor is created using the cursor() method specifying the name parameter.  To move in the dataset we use scroll() method and scrollable() method to move backward as well
  • 12. Make the changes to the database persistent conn.commit() Close communication with the database cur.close() conn.close()
  • 14. CRUD
  • 15.  cur.execute("DROP TABLE IF EXISTS tablename")  cur.execute("CREATE TABLE tablename (id serial PRIMARY KEY, num integer, data varchar)“)  cur.executemany() ??????? Create and drop table
  • 16. cur.execute("SELECT * FROM tablename") cur.execute("INSERT INTO tablename (num, data) VALUES (%s, %s)", ... (100, “apple")) insert insertmany
  • 17. Obtain data as Python objects cur.fetchone(),cur.fetchall(),cur.fetchmany(5) fetchone fetchall
  • 18.  Always be a %s, even if a different placeholder (such as a %d for integers or %f for floats) may look more appropriate: cur.execute("INSERT INTO tablename VALUES (%d)", (42,)) # WRONG cur.execute("INSERT INTO tablenameVALUES (%s)", (42,)) # correct  Named arguments are supported too using %(name)s placeholders. cur.execute( """INSERT INTO tablename (an_int, a_date, another_date, a_string) VALUES (%(int)s, %(date)s, %(date)s, %(str)s);""", {'int': 10, 'str': "O'Reilly", 'date': datetime.date(2005, 11, 18)})
  • 19.  The Python string operator % is not used: the execute() method accepts a tuple or dictionary of values as second parameter.  For positional variables binding, the second argument must always be a sequence, even if it contains a single variable:  cur.execute("INSERT INTO foo VALUES (%s)", "bar") # WRONG  cur.execute("INSERT INTO foo VALUES (%s)", ("bar")) # WRONG  cur.execute("INSERT INTO foo VALUES (%s)", ("bar",)) # correct  cur.execute("INSERT INTO foo VALUES (%s)", ["bar"]) # correct
  • 20. Python PostgreSQL None NULL Bool Bool Float Real,double Int,long Smallint,integer,bigint Decimal Numeric Str Varchar Date Date Datetime Timestamp List array Many standard Python types are adapted into SQL and returned as Python objects when a query is executed. Psycopg casts Python variables to SQL literals by type.
  • 22. cur.execute("UPDATE tablename SET price=%s WHERE id=%s", (60000, 1)) cur.execute("SELECT * FROM tablename WHERE id=%(id)s", {'id': 4 } )
  • 26. Writing image to db Reading image from db