SlideShare a Scribd company logo
A presentation on
psycopg2 python
module
by Dinesh Neupane [@neupanedinesh_] | Kathmandu
University
Psycopg2
A python driver for PostGreSQL
PostgreSQL
Python
Script
Background
 PostGreSQL database adapter for Python
Programming language
 Version 2 : original code completely rewritten for
better styling of classes for connection and cursor
 Postgres is type sensitive so we have to declare
types on each of our columns.
1
Background
● Robust engine that is implemented as a server
rather than a single file. As a server, Postgres
accepts connections from clients who can request a
SELECT, INSERT, or any other type of SQL query.
● This type of a design is called a client-server model,
where clients can interact with the server.
2
Requirements
 PostGreSQL 9.3 or higher
 Python 2.0 or higher
3
Installation
● Install python package installer (pip)
● For windows machine (to install package with all it’s
dependencies)
pip install psycopg2
4
Classes and Methods
● Connect()
Create a new database connection and returns a new
connection instance
connect("dbname=‘test_database’user=‘postgres'host='localhost'
password=‘italy'")
5
Connection Parameters
The basic connection parameters are:
● dbname – the database name (database is a
deprecated alias) user – user name used to
authenticate
● password – password used to authenticate
● host – database host address
● port – connection port number
6
Connection Example
Example:
import psycopg2
try:
conn = psycopg2.connect("dbname='test_database'
user='postgres' host='localhost' password='italy’”)
print "Connection Sucessful !! "
except:
print "unable to connect to the database"
7
Cursor()
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.
8
Cursor()
The class cursor allows interaction with the database:
● Send commands to the database using using
methods like execute() and executemany()
● Retrieve data from the database by iteration or
using methods such as fetchone(), fetchmany() or
fetchall()
● cursor.description to get the metadata
9
Cursor()
● mogrify() - Return a query string after arguments
binding. The string returned is exactly the one that
would be sent to the database running the execute()
method or similar. Example:
>>> cur.mogrify("INSERT INTO table_one VALUES(6, 'Sarad
Chaudhary', 'Banke Nepalgunj’)”)
"INSERT INTO table_one VALUES(6, 'Sarad Chaudhary', 'Banke
Nepalgunj’)”
10
Create and Drop table
CREATE TABLE student (
student_id INTEGER UNIQUE,
student_name VARCHAR(50),
phone CHAR(10),
birth_date DATE,
);
This creates a new table costumers with different
attribute fields.
11
Adaptation of Python Values to
SQL Types
Python PostgreSQL
None Null
Bool Bool
Float Real, Double
Int, Long Smallint, integer, bigint
Decimal Numeric
Str Varchar
List Array
12
Closing a database session
Make the changes to the database persistent
● Conn.commit()
Close the communication with database
● Cur.close()
● Conn.close()
13
Create and Drop table
The student table is created in the database that you
are connected to. [first schema in search path]
If you want the table to be created in some other
schema, you can prefix the table name with the
schema qualifier, for example:
CREATE TABLE another_schema.student( ... );
14
Create and Drop table
Dropping a table is much easier than creating a table.
The syntax for the DROP TABLE command is:
DROP TABLE student;
The rentals table existed in some schema other than your current
schema, you would qualify the table name:
DROP TABLE other_schema.student;
15
SQL Transactions
● If you check the postgres
database now you would
notice that there actually
isn't a users table inside it.
● This isn't a bug – it's
because of a concept
called SQL transactions.
16import psycopg2
conn=psycopg2.connect("host=loca
lhost dbname=postgres
user=postgres") cur =
conn.cursor()
cur.execute(""“
CREATE TABLE users(
id integer PRIMARY KEY,
email text,
name text,
address text )
""")
SQL Transactions
● With Postgres, we're dealing
with multiple users who could
be changing the database at
the same time.
● Let's imagine a simple
scenario where we're keeping
track of accounts for different
customers of a bank.
17import psycopg2
conn=psycopg2.connect("host=loca
lhost dbname=postgres
user=postgres") cur =
conn.cursor()
cur.execute("""
CREATE TABLE accounts(
id integer PRIMARY KEY,
name text,
balance float )
""")
SQL Transactions
● Our table looks like this:
● Let’s say Madhav gave 100 rupees to Sanjib. We could model this with
two queries:
UPDATE accounts SET balance=200 WHERE name=“Sanjib";
UPDATE accounts SET balance=100 WHERE name=“Madhav";
18
id name balance
1 Sanjib 100
2 Madhav 200
SQL Transactions
● We remove 100 rupees from Madhav, and add 100 rupees to Sanjib.
What if the second UPDATE statement has an error in it, the database
fails, or another user has a conflicting query?
● The first query would run properly, but the second would fail. That
would result in the following:
19
id name balance
1 Sanjib 200
2 Madhav 200
SQL Transactions
● Sanjib would be credited 100 rupees, but 100 rupees would not be
deducted from Madhav. This would cause the bank to lose money.
● Transactions prevent this type of behaviour by ensuring that all the
queries in a transaction block are executed at the same time. If any of
the transactions fail, the whole group fails, and no changes are made
to the database at all.
● When commit() is called, the PostgreSQL engine will run all the
queries at once.
20
DML: Insert
● Pass data to fill a query placeholders and let
Psycopg perform the correct conversion
● No more SQL injections!
>> "INSERT INTO table_one VALUES(6, 'Sarad Chaudhary', 'Banke
Nepalgunj’)”
21
DML: Insert
Example:
cur = conn.cursor()
insert_query="INSERT INTO table_one VALUES(6, 'Sarad
Chaudhary', 'Banke Nepalgunj’)”
cur.execute(insert_query)
conn.commit()
22
DML: Insert (copy_from() method)
● Method to load a file like .csv into the table of running
database
● Like the execute() method, it is attached to the Cursor object
but it contains different parameters.
● Arguments:
copy_from(f, ‘table_name’, sep=‘,’)
f=file to load(without header), table_name=table name, it should
load into, sep=delimeter
23
copy_from() method
Example:
import psycopg2
conn = psycopg2.connect("dbname='test_database' user='postgres'
host='localhost' password='italy’”)
cur = conn.cursor()
with open('name_list.csv', 'r') as f:
# no need to any other module to load csv
next(f)
# Skip the header row
cur.copy_from(f, 'table_one', sep=',’)
conn.commit()
24
DML: Delete
If you want to pass values to the DELETE statement, you use the
placeholders ( %s) in the DELETE statement and pass input
values to the second parameter of the execute() method.
The DELETE statement with a placeholder for the value of the id
field is as follows:
DELETE FROM test_table WHERE id = %s;
25
DML: Update
Execute the UPDATE statement with the input values
by calling the execute() method of the cursor object.
cur.execute(update_sql, (value1,value2))
26
Thank You

More Related Content

What's hot (20)

Top 5 Mistakes to Avoid When Writing Apache Spark Applications
Top 5 Mistakes to Avoid When Writing Apache Spark ApplicationsTop 5 Mistakes to Avoid When Writing Apache Spark Applications
Top 5 Mistakes to Avoid When Writing Apache Spark Applications
Cloudera, Inc.
 
jQuery
jQueryjQuery
jQuery
Vishwa Mohan
 
PostgreSQL Tutorial For Beginners | Edureka
PostgreSQL Tutorial For Beginners | EdurekaPostgreSQL Tutorial For Beginners | Edureka
PostgreSQL Tutorial For Beginners | Edureka
Edureka!
 
Log analysis with elastic stack
Log analysis with elastic stackLog analysis with elastic stack
Log analysis with elastic stack
Bangladesh Network Operators Group
 
The PostgreSQL Query Planner
The PostgreSQL Query PlannerThe PostgreSQL Query Planner
The PostgreSQL Query Planner
Command Prompt., Inc
 
Cosco: An Efficient Facebook-Scale Shuffle Service
Cosco: An Efficient Facebook-Scale Shuffle ServiceCosco: An Efficient Facebook-Scale Shuffle Service
Cosco: An Efficient Facebook-Scale Shuffle Service
Databricks
 
Spark shuffle introduction
Spark shuffle introductionSpark shuffle introduction
Spark shuffle introduction
colorant
 
Ajax presentation
Ajax presentationAjax presentation
Ajax presentation
Bharat_Kumawat
 
Apache kudu
Apache kuduApache kudu
Apache kudu
Asim Jalis
 
An Introduction to Elastic Search.
An Introduction to Elastic Search.An Introduction to Elastic Search.
An Introduction to Elastic Search.
Jurriaan Persyn
 
Graphql presentation
Graphql presentationGraphql presentation
Graphql presentation
Vibhor Grover
 
MySQL Database Monitoring: Must, Good and Nice to Have
MySQL Database Monitoring: Must, Good and Nice to HaveMySQL Database Monitoring: Must, Good and Nice to Have
MySQL Database Monitoring: Must, Good and Nice to Have
Sveta Smirnova
 
TiDB Introduction
TiDB IntroductionTiDB Introduction
TiDB Introduction
Morgan Tocker
 
OpenGurukul : Database : PostgreSQL
OpenGurukul : Database : PostgreSQLOpenGurukul : Database : PostgreSQL
OpenGurukul : Database : PostgreSQL
Open Gurukul
 
Search and analyze your data with elasticsearch
Search and analyze your data with elasticsearchSearch and analyze your data with elasticsearch
Search and analyze your data with elasticsearch
Anton Udovychenko
 
Spark performance tuning - Maksud Ibrahimov
Spark performance tuning - Maksud IbrahimovSpark performance tuning - Maksud Ibrahimov
Spark performance tuning - Maksud Ibrahimov
Maksud Ibrahimov
 
이것이 레디스다.
이것이 레디스다.이것이 레디스다.
이것이 레디스다.
Kris Jeong
 
Common Strategies for Improving Performance on Your Delta Lakehouse
Common Strategies for Improving Performance on Your Delta LakehouseCommon Strategies for Improving Performance on Your Delta Lakehouse
Common Strategies for Improving Performance on Your Delta Lakehouse
Databricks
 
My first 90 days with ClickHouse.pdf
My first 90 days with ClickHouse.pdfMy first 90 days with ClickHouse.pdf
My first 90 days with ClickHouse.pdf
Alkin Tezuysal
 
Advanced Node.JS Meetup
Advanced Node.JS MeetupAdvanced Node.JS Meetup
Advanced Node.JS Meetup
LINAGORA
 
Top 5 Mistakes to Avoid When Writing Apache Spark Applications
Top 5 Mistakes to Avoid When Writing Apache Spark ApplicationsTop 5 Mistakes to Avoid When Writing Apache Spark Applications
Top 5 Mistakes to Avoid When Writing Apache Spark Applications
Cloudera, Inc.
 
PostgreSQL Tutorial For Beginners | Edureka
PostgreSQL Tutorial For Beginners | EdurekaPostgreSQL Tutorial For Beginners | Edureka
PostgreSQL Tutorial For Beginners | Edureka
Edureka!
 
Cosco: An Efficient Facebook-Scale Shuffle Service
Cosco: An Efficient Facebook-Scale Shuffle ServiceCosco: An Efficient Facebook-Scale Shuffle Service
Cosco: An Efficient Facebook-Scale Shuffle Service
Databricks
 
Spark shuffle introduction
Spark shuffle introductionSpark shuffle introduction
Spark shuffle introduction
colorant
 
An Introduction to Elastic Search.
An Introduction to Elastic Search.An Introduction to Elastic Search.
An Introduction to Elastic Search.
Jurriaan Persyn
 
Graphql presentation
Graphql presentationGraphql presentation
Graphql presentation
Vibhor Grover
 
MySQL Database Monitoring: Must, Good and Nice to Have
MySQL Database Monitoring: Must, Good and Nice to HaveMySQL Database Monitoring: Must, Good and Nice to Have
MySQL Database Monitoring: Must, Good and Nice to Have
Sveta Smirnova
 
OpenGurukul : Database : PostgreSQL
OpenGurukul : Database : PostgreSQLOpenGurukul : Database : PostgreSQL
OpenGurukul : Database : PostgreSQL
Open Gurukul
 
Search and analyze your data with elasticsearch
Search and analyze your data with elasticsearchSearch and analyze your data with elasticsearch
Search and analyze your data with elasticsearch
Anton Udovychenko
 
Spark performance tuning - Maksud Ibrahimov
Spark performance tuning - Maksud IbrahimovSpark performance tuning - Maksud Ibrahimov
Spark performance tuning - Maksud Ibrahimov
Maksud Ibrahimov
 
이것이 레디스다.
이것이 레디스다.이것이 레디스다.
이것이 레디스다.
Kris Jeong
 
Common Strategies for Improving Performance on Your Delta Lakehouse
Common Strategies for Improving Performance on Your Delta LakehouseCommon Strategies for Improving Performance on Your Delta Lakehouse
Common Strategies for Improving Performance on Your Delta Lakehouse
Databricks
 
My first 90 days with ClickHouse.pdf
My first 90 days with ClickHouse.pdfMy first 90 days with ClickHouse.pdf
My first 90 days with ClickHouse.pdf
Alkin Tezuysal
 
Advanced Node.JS Meetup
Advanced Node.JS MeetupAdvanced Node.JS Meetup
Advanced Node.JS Meetup
LINAGORA
 

Similar to Connecting and using PostgreSQL database with psycopg2 [Python 2.7] (20)

Psycopg2 - Connect to PostgreSQL using Python Script
Psycopg2 - Connect to PostgreSQL using Python ScriptPsycopg2 - Connect to PostgreSQL using Python Script
Psycopg2 - Connect to PostgreSQL using Python Script
Survey Department
 
Programming with Python and PostgreSQL
Programming with Python and PostgreSQLProgramming with Python and PostgreSQL
Programming with Python and PostgreSQL
Peter Eisentraut
 
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
 
Database programming
Database programmingDatabase programming
Database programming
Shree M.L.Kakadiya MCA mahila college, Amreli
 
Database connectivity in python
Database connectivity in pythonDatabase connectivity in python
Database connectivity in python
baabtra.com - No. 1 supplier of quality freshers
 
Python database connection
Python database connectionPython database connection
Python database connection
baabtra.com - No. 1 supplier of quality freshers
 
Interface Python with MySQL.pdf
Interface Python with MySQL.pdfInterface Python with MySQL.pdf
Interface Python with MySQL.pdf
DhirajKumarBiswal
 
Relational Database Access with Python
Relational Database Access with PythonRelational Database Access with Python
Relational Database Access with Python
Mark Rees
 
Databases with SQLite3.pdf
Databases with SQLite3.pdfDatabases with SQLite3.pdf
Databases with SQLite3.pdf
Deepika,Assistant Professor,PES College of Engineering ,Mandya
 
SQL-Connectivity python for beginners easy explanation with concepts and outp...
SQL-Connectivity python for beginners easy explanation with concepts and outp...SQL-Connectivity python for beginners easy explanation with concepts and outp...
SQL-Connectivity python for beginners easy explanation with concepts and outp...
harshitagrawal2608
 
Relational Database Access with Python ‘sans’ ORM
Relational Database Access with Python ‘sans’ ORM  Relational Database Access with Python ‘sans’ ORM
Relational Database Access with Python ‘sans’ ORM
Mark Rees
 
PostgreSQL- An Introduction
PostgreSQL- An IntroductionPostgreSQL- An Introduction
PostgreSQL- An Introduction
Smita Prasad
 
015. Interface Python with sql interface ppt class 12
015. Interface Python with sql interface ppt class 12015. Interface Python with sql interface ppt class 12
015. Interface Python with sql interface ppt class 12
Shuvanth
 
Python database access
Python database accessPython database access
Python database access
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
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
 
PYTHON_DATABASE_CONNECTIVITY_for_class_12.pptx
PYTHON_DATABASE_CONNECTIVITY_for_class_12.pptxPYTHON_DATABASE_CONNECTIVITY_for_class_12.pptx
PYTHON_DATABASE_CONNECTIVITY_for_class_12.pptx
HistoryScienceWorld
 
SQLite 3 chapter 4 BCA Notes Python NEP syllabus
SQLite 3 chapter 4 BCA Notes Python NEP syllabusSQLite 3 chapter 4 BCA Notes Python NEP syllabus
SQLite 3 chapter 4 BCA Notes Python NEP syllabus
Subrahmanya6
 
python db connection samples and program
python db connection samples and programpython db connection samples and program
python db connection samples and program
usha raj
 
AmI 2015 - Databases in Python
AmI 2015 - Databases in PythonAmI 2015 - Databases in Python
AmI 2015 - Databases in Python
Fulvio Corno
 
Database Connectivity using Python and MySQL
Database Connectivity using Python and MySQLDatabase Connectivity using Python and MySQL
Database Connectivity using Python and MySQL
devsuchaye
 
Psycopg2 - Connect to PostgreSQL using Python Script
Psycopg2 - Connect to PostgreSQL using Python ScriptPsycopg2 - Connect to PostgreSQL using Python Script
Psycopg2 - Connect to PostgreSQL using Python Script
Survey Department
 
Programming with Python and PostgreSQL
Programming with Python and PostgreSQLProgramming with Python and PostgreSQL
Programming with Python and PostgreSQL
Peter Eisentraut
 
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
 
Interface Python with MySQL.pdf
Interface Python with MySQL.pdfInterface Python with MySQL.pdf
Interface Python with MySQL.pdf
DhirajKumarBiswal
 
Relational Database Access with Python
Relational Database Access with PythonRelational Database Access with Python
Relational Database Access with Python
Mark Rees
 
SQL-Connectivity python for beginners easy explanation with concepts and outp...
SQL-Connectivity python for beginners easy explanation with concepts and outp...SQL-Connectivity python for beginners easy explanation with concepts and outp...
SQL-Connectivity python for beginners easy explanation with concepts and outp...
harshitagrawal2608
 
Relational Database Access with Python ‘sans’ ORM
Relational Database Access with Python ‘sans’ ORM  Relational Database Access with Python ‘sans’ ORM
Relational Database Access with Python ‘sans’ ORM
Mark Rees
 
PostgreSQL- An Introduction
PostgreSQL- An IntroductionPostgreSQL- An Introduction
PostgreSQL- An Introduction
Smita Prasad
 
015. Interface Python with sql interface ppt class 12
015. Interface Python with sql interface ppt class 12015. Interface Python with sql interface ppt class 12
015. Interface Python with sql interface ppt class 12
Shuvanth
 
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
 
PYTHON_DATABASE_CONNECTIVITY_for_class_12.pptx
PYTHON_DATABASE_CONNECTIVITY_for_class_12.pptxPYTHON_DATABASE_CONNECTIVITY_for_class_12.pptx
PYTHON_DATABASE_CONNECTIVITY_for_class_12.pptx
HistoryScienceWorld
 
SQLite 3 chapter 4 BCA Notes Python NEP syllabus
SQLite 3 chapter 4 BCA Notes Python NEP syllabusSQLite 3 chapter 4 BCA Notes Python NEP syllabus
SQLite 3 chapter 4 BCA Notes Python NEP syllabus
Subrahmanya6
 
python db connection samples and program
python db connection samples and programpython db connection samples and program
python db connection samples and program
usha raj
 
AmI 2015 - Databases in Python
AmI 2015 - Databases in PythonAmI 2015 - Databases in Python
AmI 2015 - Databases in Python
Fulvio Corno
 
Database Connectivity using Python and MySQL
Database Connectivity using Python and MySQLDatabase Connectivity using Python and MySQL
Database Connectivity using Python and MySQL
devsuchaye
 
Ad

Recently uploaded (20)

Video Games and Artificial-Realities.pptx
Video Games and Artificial-Realities.pptxVideo Games and Artificial-Realities.pptx
Video Games and Artificial-Realities.pptx
HadiBadri1
 
Utilizing Biomedical Waste for Sustainable Brick Manufacturing: A Novel Appro...
Utilizing Biomedical Waste for Sustainable Brick Manufacturing: A Novel Appro...Utilizing Biomedical Waste for Sustainable Brick Manufacturing: A Novel Appro...
Utilizing Biomedical Waste for Sustainable Brick Manufacturing: A Novel Appro...
IRJET Journal
 
UNIT-5-PPT Computer Control Power of Power System
UNIT-5-PPT Computer Control Power of Power SystemUNIT-5-PPT Computer Control Power of Power System
UNIT-5-PPT Computer Control Power of Power System
Sridhar191373
 
Numerical Investigation of the Aerodynamic Characteristics for a Darrieus H-t...
Numerical Investigation of the Aerodynamic Characteristics for a Darrieus H-t...Numerical Investigation of the Aerodynamic Characteristics for a Darrieus H-t...
Numerical Investigation of the Aerodynamic Characteristics for a Darrieus H-t...
Mohamed905031
 
Highway Engineering - Pavement materials
Highway Engineering - Pavement materialsHighway Engineering - Pavement materials
Highway Engineering - Pavement materials
AmrutaBhosale9
 
[HIFLUX] Lok Fitting&Valve Catalog 2025 (Eng)
[HIFLUX] Lok Fitting&Valve Catalog 2025 (Eng)[HIFLUX] Lok Fitting&Valve Catalog 2025 (Eng)
[HIFLUX] Lok Fitting&Valve Catalog 2025 (Eng)
하이플럭스 / HIFLUX Co., Ltd.
 
Pruebas y Solucion de problemas empresariales en redes de Fibra Optica
Pruebas y Solucion de problemas empresariales en redes de Fibra OpticaPruebas y Solucion de problemas empresariales en redes de Fibra Optica
Pruebas y Solucion de problemas empresariales en redes de Fibra Optica
OmarAlfredoDelCastil
 
Digital Crime – Substantive Criminal Law – General Conditions – Offenses – In...
Digital Crime – Substantive Criminal Law – General Conditions – Offenses – In...Digital Crime – Substantive Criminal Law – General Conditions – Offenses – In...
Digital Crime – Substantive Criminal Law – General Conditions – Offenses – In...
ManiMaran230751
 
Software Developer Portfolio: Backend Architecture & Performance Optimization
Software Developer Portfolio: Backend Architecture & Performance OptimizationSoftware Developer Portfolio: Backend Architecture & Performance Optimization
Software Developer Portfolio: Backend Architecture & Performance Optimization
kiwoong (daniel) kim
 
Tesia Dobrydnia - A Leader In Her Industry
Tesia Dobrydnia - A Leader In Her IndustryTesia Dobrydnia - A Leader In Her Industry
Tesia Dobrydnia - A Leader In Her Industry
Tesia Dobrydnia
 
fy06_46f6-ht30_22_oil_gas_industry_guidelines.ppt
fy06_46f6-ht30_22_oil_gas_industry_guidelines.pptfy06_46f6-ht30_22_oil_gas_industry_guidelines.ppt
fy06_46f6-ht30_22_oil_gas_industry_guidelines.ppt
sukarnoamin
 
Influence line diagram for truss in a robust
Influence line diagram for truss in a robustInfluence line diagram for truss in a robust
Influence line diagram for truss in a robust
ParthaSengupta26
 
May 2025 - Top 10 Read Articles in Artificial Intelligence and Applications (...
May 2025 - Top 10 Read Articles in Artificial Intelligence and Applications (...May 2025 - Top 10 Read Articles in Artificial Intelligence and Applications (...
May 2025 - Top 10 Read Articles in Artificial Intelligence and Applications (...
gerogepatton
 
Fresh concrete Workability Measurement
Fresh concrete  Workability  MeasurementFresh concrete  Workability  Measurement
Fresh concrete Workability Measurement
SasiVarman5
 
world subdivision.pdf...................
world subdivision.pdf...................world subdivision.pdf...................
world subdivision.pdf...................
bmmederos12
 
ISO 4548-9 Oil Filter Anti Drain Catalogue.pdf
ISO 4548-9 Oil Filter Anti Drain Catalogue.pdfISO 4548-9 Oil Filter Anti Drain Catalogue.pdf
ISO 4548-9 Oil Filter Anti Drain Catalogue.pdf
FILTRATION ENGINEERING & CUNSULTANT
 
9aeb2aae-3b85-47a5-9776-154883bbae57.pdf
9aeb2aae-3b85-47a5-9776-154883bbae57.pdf9aeb2aae-3b85-47a5-9776-154883bbae57.pdf
9aeb2aae-3b85-47a5-9776-154883bbae57.pdf
RishabhGupta578788
 
What is dbms architecture, components of dbms architecture and types of dbms ...
What is dbms architecture, components of dbms architecture and types of dbms ...What is dbms architecture, components of dbms architecture and types of dbms ...
What is dbms architecture, components of dbms architecture and types of dbms ...
cyhuutjdoazdwrnubt
 
"The Enigmas of the Riemann Hypothesis" by Julio Chai
"The Enigmas of the Riemann Hypothesis" by Julio Chai"The Enigmas of the Riemann Hypothesis" by Julio Chai
"The Enigmas of the Riemann Hypothesis" by Julio Chai
Julio Chai
 
MODULE 4 BUILDING PLANNING AND DESIGN SY BTECH HVAC SYSTEM IN BUILDING
MODULE 4 BUILDING PLANNING AND DESIGN SY BTECH HVAC SYSTEM IN BUILDINGMODULE 4 BUILDING PLANNING AND DESIGN SY BTECH HVAC SYSTEM IN BUILDING
MODULE 4 BUILDING PLANNING AND DESIGN SY BTECH HVAC SYSTEM IN BUILDING
Dr. BASWESHWAR JIRWANKAR
 
Video Games and Artificial-Realities.pptx
Video Games and Artificial-Realities.pptxVideo Games and Artificial-Realities.pptx
Video Games and Artificial-Realities.pptx
HadiBadri1
 
Utilizing Biomedical Waste for Sustainable Brick Manufacturing: A Novel Appro...
Utilizing Biomedical Waste for Sustainable Brick Manufacturing: A Novel Appro...Utilizing Biomedical Waste for Sustainable Brick Manufacturing: A Novel Appro...
Utilizing Biomedical Waste for Sustainable Brick Manufacturing: A Novel Appro...
IRJET Journal
 
UNIT-5-PPT Computer Control Power of Power System
UNIT-5-PPT Computer Control Power of Power SystemUNIT-5-PPT Computer Control Power of Power System
UNIT-5-PPT Computer Control Power of Power System
Sridhar191373
 
Numerical Investigation of the Aerodynamic Characteristics for a Darrieus H-t...
Numerical Investigation of the Aerodynamic Characteristics for a Darrieus H-t...Numerical Investigation of the Aerodynamic Characteristics for a Darrieus H-t...
Numerical Investigation of the Aerodynamic Characteristics for a Darrieus H-t...
Mohamed905031
 
Highway Engineering - Pavement materials
Highway Engineering - Pavement materialsHighway Engineering - Pavement materials
Highway Engineering - Pavement materials
AmrutaBhosale9
 
Pruebas y Solucion de problemas empresariales en redes de Fibra Optica
Pruebas y Solucion de problemas empresariales en redes de Fibra OpticaPruebas y Solucion de problemas empresariales en redes de Fibra Optica
Pruebas y Solucion de problemas empresariales en redes de Fibra Optica
OmarAlfredoDelCastil
 
Digital Crime – Substantive Criminal Law – General Conditions – Offenses – In...
Digital Crime – Substantive Criminal Law – General Conditions – Offenses – In...Digital Crime – Substantive Criminal Law – General Conditions – Offenses – In...
Digital Crime – Substantive Criminal Law – General Conditions – Offenses – In...
ManiMaran230751
 
Software Developer Portfolio: Backend Architecture & Performance Optimization
Software Developer Portfolio: Backend Architecture & Performance OptimizationSoftware Developer Portfolio: Backend Architecture & Performance Optimization
Software Developer Portfolio: Backend Architecture & Performance Optimization
kiwoong (daniel) kim
 
Tesia Dobrydnia - A Leader In Her Industry
Tesia Dobrydnia - A Leader In Her IndustryTesia Dobrydnia - A Leader In Her Industry
Tesia Dobrydnia - A Leader In Her Industry
Tesia Dobrydnia
 
fy06_46f6-ht30_22_oil_gas_industry_guidelines.ppt
fy06_46f6-ht30_22_oil_gas_industry_guidelines.pptfy06_46f6-ht30_22_oil_gas_industry_guidelines.ppt
fy06_46f6-ht30_22_oil_gas_industry_guidelines.ppt
sukarnoamin
 
Influence line diagram for truss in a robust
Influence line diagram for truss in a robustInfluence line diagram for truss in a robust
Influence line diagram for truss in a robust
ParthaSengupta26
 
May 2025 - Top 10 Read Articles in Artificial Intelligence and Applications (...
May 2025 - Top 10 Read Articles in Artificial Intelligence and Applications (...May 2025 - Top 10 Read Articles in Artificial Intelligence and Applications (...
May 2025 - Top 10 Read Articles in Artificial Intelligence and Applications (...
gerogepatton
 
Fresh concrete Workability Measurement
Fresh concrete  Workability  MeasurementFresh concrete  Workability  Measurement
Fresh concrete Workability Measurement
SasiVarman5
 
world subdivision.pdf...................
world subdivision.pdf...................world subdivision.pdf...................
world subdivision.pdf...................
bmmederos12
 
9aeb2aae-3b85-47a5-9776-154883bbae57.pdf
9aeb2aae-3b85-47a5-9776-154883bbae57.pdf9aeb2aae-3b85-47a5-9776-154883bbae57.pdf
9aeb2aae-3b85-47a5-9776-154883bbae57.pdf
RishabhGupta578788
 
What is dbms architecture, components of dbms architecture and types of dbms ...
What is dbms architecture, components of dbms architecture and types of dbms ...What is dbms architecture, components of dbms architecture and types of dbms ...
What is dbms architecture, components of dbms architecture and types of dbms ...
cyhuutjdoazdwrnubt
 
"The Enigmas of the Riemann Hypothesis" by Julio Chai
"The Enigmas of the Riemann Hypothesis" by Julio Chai"The Enigmas of the Riemann Hypothesis" by Julio Chai
"The Enigmas of the Riemann Hypothesis" by Julio Chai
Julio Chai
 
MODULE 4 BUILDING PLANNING AND DESIGN SY BTECH HVAC SYSTEM IN BUILDING
MODULE 4 BUILDING PLANNING AND DESIGN SY BTECH HVAC SYSTEM IN BUILDINGMODULE 4 BUILDING PLANNING AND DESIGN SY BTECH HVAC SYSTEM IN BUILDING
MODULE 4 BUILDING PLANNING AND DESIGN SY BTECH HVAC SYSTEM IN BUILDING
Dr. BASWESHWAR JIRWANKAR
 
Ad

Connecting and using PostgreSQL database with psycopg2 [Python 2.7]

  • 1. A presentation on psycopg2 python module by Dinesh Neupane [@neupanedinesh_] | Kathmandu University
  • 2. Psycopg2 A python driver for PostGreSQL PostgreSQL Python Script
  • 3. Background  PostGreSQL database adapter for Python Programming language  Version 2 : original code completely rewritten for better styling of classes for connection and cursor  Postgres is type sensitive so we have to declare types on each of our columns. 1
  • 4. Background ● Robust engine that is implemented as a server rather than a single file. As a server, Postgres accepts connections from clients who can request a SELECT, INSERT, or any other type of SQL query. ● This type of a design is called a client-server model, where clients can interact with the server. 2
  • 5. Requirements  PostGreSQL 9.3 or higher  Python 2.0 or higher 3
  • 6. Installation ● Install python package installer (pip) ● For windows machine (to install package with all it’s dependencies) pip install psycopg2 4
  • 7. Classes and Methods ● Connect() Create a new database connection and returns a new connection instance connect("dbname=‘test_database’user=‘postgres'host='localhost' password=‘italy'") 5
  • 8. Connection Parameters The basic connection parameters are: ● dbname – the database name (database is a deprecated alias) user – user name used to authenticate ● password – password used to authenticate ● host – database host address ● port – connection port number 6
  • 9. Connection Example Example: import psycopg2 try: conn = psycopg2.connect("dbname='test_database' user='postgres' host='localhost' password='italy’”) print "Connection Sucessful !! " except: print "unable to connect to the database" 7
  • 10. Cursor() 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. 8
  • 11. Cursor() The class cursor allows interaction with the database: ● Send commands to the database using using methods like execute() and executemany() ● Retrieve data from the database by iteration or using methods such as fetchone(), fetchmany() or fetchall() ● cursor.description to get the metadata 9
  • 12. Cursor() ● mogrify() - Return a query string after arguments binding. The string returned is exactly the one that would be sent to the database running the execute() method or similar. Example: >>> cur.mogrify("INSERT INTO table_one VALUES(6, 'Sarad Chaudhary', 'Banke Nepalgunj’)”) "INSERT INTO table_one VALUES(6, 'Sarad Chaudhary', 'Banke Nepalgunj’)” 10
  • 13. Create and Drop table CREATE TABLE student ( student_id INTEGER UNIQUE, student_name VARCHAR(50), phone CHAR(10), birth_date DATE, ); This creates a new table costumers with different attribute fields. 11
  • 14. Adaptation of Python Values to SQL Types Python PostgreSQL None Null Bool Bool Float Real, Double Int, Long Smallint, integer, bigint Decimal Numeric Str Varchar List Array 12
  • 15. Closing a database session Make the changes to the database persistent ● Conn.commit() Close the communication with database ● Cur.close() ● Conn.close() 13
  • 16. Create and Drop table The student table is created in the database that you are connected to. [first schema in search path] If you want the table to be created in some other schema, you can prefix the table name with the schema qualifier, for example: CREATE TABLE another_schema.student( ... ); 14
  • 17. Create and Drop table Dropping a table is much easier than creating a table. The syntax for the DROP TABLE command is: DROP TABLE student; The rentals table existed in some schema other than your current schema, you would qualify the table name: DROP TABLE other_schema.student; 15
  • 18. SQL Transactions ● If you check the postgres database now you would notice that there actually isn't a users table inside it. ● This isn't a bug – it's because of a concept called SQL transactions. 16import psycopg2 conn=psycopg2.connect("host=loca lhost dbname=postgres user=postgres") cur = conn.cursor() cur.execute(""“ CREATE TABLE users( id integer PRIMARY KEY, email text, name text, address text ) """)
  • 19. SQL Transactions ● With Postgres, we're dealing with multiple users who could be changing the database at the same time. ● Let's imagine a simple scenario where we're keeping track of accounts for different customers of a bank. 17import psycopg2 conn=psycopg2.connect("host=loca lhost dbname=postgres user=postgres") cur = conn.cursor() cur.execute(""" CREATE TABLE accounts( id integer PRIMARY KEY, name text, balance float ) """)
  • 20. SQL Transactions ● Our table looks like this: ● Let’s say Madhav gave 100 rupees to Sanjib. We could model this with two queries: UPDATE accounts SET balance=200 WHERE name=“Sanjib"; UPDATE accounts SET balance=100 WHERE name=“Madhav"; 18 id name balance 1 Sanjib 100 2 Madhav 200
  • 21. SQL Transactions ● We remove 100 rupees from Madhav, and add 100 rupees to Sanjib. What if the second UPDATE statement has an error in it, the database fails, or another user has a conflicting query? ● The first query would run properly, but the second would fail. That would result in the following: 19 id name balance 1 Sanjib 200 2 Madhav 200
  • 22. SQL Transactions ● Sanjib would be credited 100 rupees, but 100 rupees would not be deducted from Madhav. This would cause the bank to lose money. ● Transactions prevent this type of behaviour by ensuring that all the queries in a transaction block are executed at the same time. If any of the transactions fail, the whole group fails, and no changes are made to the database at all. ● When commit() is called, the PostgreSQL engine will run all the queries at once. 20
  • 23. DML: Insert ● Pass data to fill a query placeholders and let Psycopg perform the correct conversion ● No more SQL injections! >> "INSERT INTO table_one VALUES(6, 'Sarad Chaudhary', 'Banke Nepalgunj’)” 21
  • 24. DML: Insert Example: cur = conn.cursor() insert_query="INSERT INTO table_one VALUES(6, 'Sarad Chaudhary', 'Banke Nepalgunj’)” cur.execute(insert_query) conn.commit() 22
  • 25. DML: Insert (copy_from() method) ● Method to load a file like .csv into the table of running database ● Like the execute() method, it is attached to the Cursor object but it contains different parameters. ● Arguments: copy_from(f, ‘table_name’, sep=‘,’) f=file to load(without header), table_name=table name, it should load into, sep=delimeter 23
  • 26. copy_from() method Example: import psycopg2 conn = psycopg2.connect("dbname='test_database' user='postgres' host='localhost' password='italy’”) cur = conn.cursor() with open('name_list.csv', 'r') as f: # no need to any other module to load csv next(f) # Skip the header row cur.copy_from(f, 'table_one', sep=',’) conn.commit() 24
  • 27. DML: Delete If you want to pass values to the DELETE statement, you use the placeholders ( %s) in the DELETE statement and pass input values to the second parameter of the execute() method. The DELETE statement with a placeholder for the value of the id field is as follows: DELETE FROM test_table WHERE id = %s; 25
  • 28. DML: Update Execute the UPDATE statement with the input values by calling the execute() method of the cursor object. cur.execute(update_sql, (value1,value2)) 26