SlideShare a Scribd company logo
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
Ad

More Related Content

What's hot (20)

Bca i-fundamental of computer-u-2- application and system software
Bca  i-fundamental of  computer-u-2- application and system softwareBca  i-fundamental of  computer-u-2- application and system software
Bca i-fundamental of computer-u-2- application and system software
Rai University
 
Backtracking
BacktrackingBacktracking
Backtracking
subhradeep mitra
 
Tsp branch and bound
Tsp branch and boundTsp branch and bound
Tsp branch and bound
Dr.DHANALAKSHMI SENTHILKUMAR
 
scope of python
scope of pythonscope of python
scope of python
Dwarak Besant
 
Lecture 3 Computer Science Research SEM1 22_23 (1).pptx
Lecture 3 Computer Science Research SEM1 22_23 (1).pptxLecture 3 Computer Science Research SEM1 22_23 (1).pptx
Lecture 3 Computer Science Research SEM1 22_23 (1).pptx
NabilaHassan13
 
Manual ejercicios
Manual ejerciciosManual ejercicios
Manual ejercicios
Maria Isabel Gonzales Valero
 
Wpf Introduction
Wpf IntroductionWpf Introduction
Wpf Introduction
Martha Rotter
 
PPT on Data Science Using Python
PPT on Data Science Using PythonPPT on Data Science Using Python
PPT on Data Science Using Python
NishantKumar1179
 
Unified Modeling Language
Unified Modeling LanguageUnified Modeling Language
Unified Modeling Language
surana college
 
SOFTWARE PROJECT PLANNING on Software Engineering
SOFTWARE PROJECT PLANNING on Software EngineeringSOFTWARE PROJECT PLANNING on Software Engineering
SOFTWARE PROJECT PLANNING on Software Engineering
work90665
 
Networking in python by Rj
Networking in python by RjNetworking in python by Rj
Networking in python by Rj
Shree M.L.Kakadiya MCA mahila college, Amreli
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
Agung Wahyudi
 
Intro to Jupyter Notebooks
Intro to Jupyter NotebooksIntro to Jupyter Notebooks
Intro to Jupyter Notebooks
Francis Michael Bautista
 
Introduction to Python IDLE | IDLE Tutorial | Edureka
Introduction to Python IDLE | IDLE Tutorial | EdurekaIntroduction to Python IDLE | IDLE Tutorial | Edureka
Introduction to Python IDLE | IDLE Tutorial | Edureka
Edureka!
 
Theory of Computation Unit 2
Theory of Computation Unit 2Theory of Computation Unit 2
Theory of Computation Unit 2
Jena Catherine Bel D
 
PROTOTYPE MODEL
PROTOTYPE MODELPROTOTYPE MODEL
PROTOTYPE MODEL
shenagarg44
 
Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)
Pedro Rodrigues
 
Python basics
Python basicsPython basics
Python basics
Jyoti shukla
 
Statistics Using Python | Statistics Python Tutorial | Python Certification T...
Statistics Using Python | Statistics Python Tutorial | Python Certification T...Statistics Using Python | Statistics Python Tutorial | Python Certification T...
Statistics Using Python | Statistics Python Tutorial | Python Certification T...
Edureka!
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
VidhyaSenthil
 
Bca i-fundamental of computer-u-2- application and system software
Bca  i-fundamental of  computer-u-2- application and system softwareBca  i-fundamental of  computer-u-2- application and system software
Bca i-fundamental of computer-u-2- application and system software
Rai University
 
Lecture 3 Computer Science Research SEM1 22_23 (1).pptx
Lecture 3 Computer Science Research SEM1 22_23 (1).pptxLecture 3 Computer Science Research SEM1 22_23 (1).pptx
Lecture 3 Computer Science Research SEM1 22_23 (1).pptx
NabilaHassan13
 
PPT on Data Science Using Python
PPT on Data Science Using PythonPPT on Data Science Using Python
PPT on Data Science Using Python
NishantKumar1179
 
Unified Modeling Language
Unified Modeling LanguageUnified Modeling Language
Unified Modeling Language
surana college
 
SOFTWARE PROJECT PLANNING on Software Engineering
SOFTWARE PROJECT PLANNING on Software EngineeringSOFTWARE PROJECT PLANNING on Software Engineering
SOFTWARE PROJECT PLANNING on Software Engineering
work90665
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
Agung Wahyudi
 
Introduction to Python IDLE | IDLE Tutorial | Edureka
Introduction to Python IDLE | IDLE Tutorial | EdurekaIntroduction to Python IDLE | IDLE Tutorial | Edureka
Introduction to Python IDLE | IDLE Tutorial | Edureka
Edureka!
 
Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)
Pedro Rodrigues
 
Statistics Using Python | Statistics Python Tutorial | Python Certification T...
Statistics Using Python | Statistics Python Tutorial | Python Certification T...Statistics Using Python | Statistics Python Tutorial | Python Certification T...
Statistics Using Python | Statistics Python Tutorial | Python Certification T...
Edureka!
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
VidhyaSenthil
 

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

Hadoop Integration in Cassandra
Hadoop Integration in CassandraHadoop Integration in Cassandra
Hadoop Integration in Cassandra
Jairam 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 JUG
Matthew 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
 
TopicMapReduceComet log analysis by using splunk
TopicMapReduceComet log analysis by using splunkTopicMapReduceComet log analysis by using splunk
TopicMapReduceComet log analysis by using splunk
akashkale0756
 
Spark_Documentation_Template1
Spark_Documentation_Template1Spark_Documentation_Template1
Spark_Documentation_Template1
Nagavarunkumar Kolla
 
Simple Apache Spark Introduction - Part 2
Simple Apache Spark Introduction - Part 2Simple Apache Spark Introduction - Part 2
Simple Apache Spark Introduction - Part 2
chiragmota91
 
Introduction to Scalding and Monoids
Introduction to Scalding and MonoidsIntroduction to Scalding and Monoids
Introduction to Scalding and Monoids
Hugo Gävert
 
Programming with Python and PostgreSQL
Programming with Python and PostgreSQLProgramming with Python and PostgreSQL
Programming with Python and PostgreSQL
Peter Eisentraut
 
Phil Bartie QGIS PLPython
Phil Bartie QGIS PLPythonPhil Bartie QGIS PLPython
Phil Bartie QGIS PLPython
Ross McDonald
 
Python postgre sql a wonderful wedding
Python postgre sql   a wonderful weddingPython postgre sql   a wonderful wedding
Python postgre sql a wonderful wedding
Sté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
 
9 Python programming notes for ktu physics and computer application semester 4
9 Python programming notes for ktu  physics and computer application semester 49 Python programming notes for ktu  physics and computer application semester 4
9 Python programming notes for ktu physics and computer application semester 4
ebindboby1
 
What is new in Java 8
What is new in Java 8What is new in Java 8
What is new in Java 8
Sandeep Kr. Singh
 
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
Desing Pathshala
 
Database Connectivity using Python and MySQL
Database Connectivity using Python and MySQLDatabase Connectivity using Python and MySQL
Database Connectivity using Python and MySQL
devsuchaye
 
Python database connection
Python database connectionPython database connection
Python database connection
baabtra.com - No. 1 supplier of quality freshers
 
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
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
Dmitry Buzdin
 
Hadoop Integration in Cassandra
Hadoop Integration in CassandraHadoop Integration in Cassandra
Hadoop Integration in Cassandra
Jairam 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 JUG
Matthew 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
 
TopicMapReduceComet log analysis by using splunk
TopicMapReduceComet log analysis by using splunkTopicMapReduceComet log analysis by using splunk
TopicMapReduceComet log analysis by using splunk
akashkale0756
 
Simple Apache Spark Introduction - Part 2
Simple Apache Spark Introduction - Part 2Simple Apache Spark Introduction - Part 2
Simple Apache Spark Introduction - Part 2
chiragmota91
 
Introduction to Scalding and Monoids
Introduction to Scalding and MonoidsIntroduction to Scalding and Monoids
Introduction to Scalding and Monoids
Hugo Gävert
 
Programming with Python and PostgreSQL
Programming with Python and PostgreSQLProgramming with Python and PostgreSQL
Programming with Python and PostgreSQL
Peter Eisentraut
 
Phil Bartie QGIS PLPython
Phil Bartie QGIS PLPythonPhil Bartie QGIS PLPython
Phil Bartie QGIS PLPython
Ross McDonald
 
Python postgre sql a wonderful wedding
Python postgre sql   a wonderful weddingPython postgre sql   a wonderful wedding
Python postgre sql a wonderful wedding
Sté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
 
9 Python programming notes for ktu physics and computer application semester 4
9 Python programming notes for ktu  physics and computer application semester 49 Python programming notes for ktu  physics and computer application semester 4
9 Python programming notes for ktu physics and computer application semester 4
ebindboby1
 
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
Desing Pathshala
 
Database Connectivity using Python and MySQL
Database Connectivity using Python and MySQLDatabase Connectivity using Python and MySQL
Database Connectivity using Python and MySQL
devsuchaye
 
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
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
Dmitry Buzdin
 
Ad

Recently uploaded (20)

theory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptxtheory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptx
sanchezvanessa7896
 
Machine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptxMachine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptx
rajeswari89780
 
Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.
anuragmk56
 
The Gaussian Process Modeling Module in UQLab
The Gaussian Process Modeling Module in UQLabThe Gaussian Process Modeling Module in UQLab
The Gaussian Process Modeling Module in UQLab
Journal of Soft Computing in Civil Engineering
 
Reagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptxReagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptx
AlejandroOdio
 
15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...
IJCSES Journal
 
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design ThinkingDT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DhruvChotaliya2
 
Introduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptxIntroduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptx
AS1920
 
Mathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdfMathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdf
TalhaShahid49
 
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptxExplainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
MahaveerVPandit
 
International Journal of Distributed and Parallel systems (IJDPS)
International Journal of Distributed and Parallel systems (IJDPS)International Journal of Distributed and Parallel systems (IJDPS)
International Journal of Distributed and Parallel systems (IJDPS)
samueljackson3773
 
Data Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptxData Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptx
RushaliDeshmukh2
 
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E..."Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
Infopitaara
 
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptxLidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
RishavKumar530754
 
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdfRICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
MohamedAbdelkader115
 
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITYADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ijscai
 
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
inmishra17121973
 
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G..."Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
Infopitaara
 
railway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forgingrailway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forging
Javad Kadkhodapour
 
Smart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptxSmart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptx
rushikeshnavghare94
 
theory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptxtheory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptx
sanchezvanessa7896
 
Machine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptxMachine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptx
rajeswari89780
 
Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.
anuragmk56
 
Reagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptxReagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptx
AlejandroOdio
 
15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...
IJCSES Journal
 
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design ThinkingDT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DhruvChotaliya2
 
Introduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptxIntroduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptx
AS1920
 
Mathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdfMathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdf
TalhaShahid49
 
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptxExplainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
MahaveerVPandit
 
International Journal of Distributed and Parallel systems (IJDPS)
International Journal of Distributed and Parallel systems (IJDPS)International Journal of Distributed and Parallel systems (IJDPS)
International Journal of Distributed and Parallel systems (IJDPS)
samueljackson3773
 
Data Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptxData Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptx
RushaliDeshmukh2
 
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E..."Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
Infopitaara
 
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptxLidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
RishavKumar530754
 
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdfRICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
MohamedAbdelkader115
 
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITYADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ijscai
 
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
inmishra17121973
 
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G..."Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
Infopitaara
 
railway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forgingrailway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forging
Javad Kadkhodapour
 
Smart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptxSmart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptx
rushikeshnavghare94
 
Ad

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