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

Optimising Geospatial Queries with Dynamic File Pruning
Optimising Geospatial Queries with Dynamic File PruningOptimising Geospatial Queries with Dynamic File Pruning
Optimising Geospatial Queries with Dynamic File Pruning
Databricks
 
Presentation upgrade, migrate & consolidate to oracle database 12c &amp...
Presentation   upgrade, migrate & consolidate to oracle database 12c &amp...Presentation   upgrade, migrate & consolidate to oracle database 12c &amp...
Presentation upgrade, migrate & consolidate to oracle database 12c &amp...
solarisyougood
 
EM12c: Capacity Planning with OEM Metrics
EM12c: Capacity Planning with OEM MetricsEM12c: Capacity Planning with OEM Metrics
EM12c: Capacity Planning with OEM Metrics
Maaz Anjum
 
Performance Stability, Tips and Tricks and Underscores
Performance Stability, Tips and Tricks and UnderscoresPerformance Stability, Tips and Tricks and Underscores
Performance Stability, Tips and Tricks and Underscores
Jitendra Singh
 
Designing Apache Hudi for Incremental Processing With Vinoth Chandar and Etha...
Designing Apache Hudi for Incremental Processing With Vinoth Chandar and Etha...Designing Apache Hudi for Incremental Processing With Vinoth Chandar and Etha...
Designing Apache Hudi for Incremental Processing With Vinoth Chandar and Etha...
HostedbyConfluent
 
Part1 of SQL Tuning Workshop - Understanding the Optimizer
Part1 of SQL Tuning Workshop - Understanding the OptimizerPart1 of SQL Tuning Workshop - Understanding the Optimizer
Part1 of SQL Tuning Workshop - Understanding the Optimizer
Maria Colgan
 
MariaDB 마이그레이션 - 네오클로바
MariaDB 마이그레이션 - 네오클로바MariaDB 마이그레이션 - 네오클로바
MariaDB 마이그레이션 - 네오클로바
NeoClova
 
Introduction to Greenplum
Introduction to GreenplumIntroduction to Greenplum
Introduction to Greenplum
Dave Cramer
 
MySQL Administrator 2021 - 네오클로바
MySQL Administrator 2021 - 네오클로바MySQL Administrator 2021 - 네오클로바
MySQL Administrator 2021 - 네오클로바
NeoClova
 
Understanding my database through SQL*Plus using the free tool eDB360
Understanding my database through SQL*Plus using the free tool eDB360Understanding my database through SQL*Plus using the free tool eDB360
Understanding my database through SQL*Plus using the free tool eDB360
Carlos Sierra
 
Linux tuning to improve PostgreSQL performance
Linux tuning to improve PostgreSQL performanceLinux tuning to improve PostgreSQL performance
Linux tuning to improve PostgreSQL performance
PostgreSQL-Consulting
 
Datastage Introduction To Data Warehousing
Datastage Introduction To Data WarehousingDatastage Introduction To Data Warehousing
Datastage Introduction To Data Warehousing
Vibrant Technologies & Computers
 
Oracle RAC 19c: Best Practices and Secret Internals
Oracle RAC 19c: Best Practices and Secret InternalsOracle RAC 19c: Best Practices and Secret Internals
Oracle RAC 19c: Best Practices and Secret Internals
Anil Nair
 
YugabyteDB - Distributed SQL Database on Kubernetes
YugabyteDB - Distributed SQL Database on KubernetesYugabyteDB - Distributed SQL Database on Kubernetes
YugabyteDB - Distributed SQL Database on Kubernetes
DoKC
 
BI, Reporting and Analytics on Apache Cassandra
BI, Reporting and Analytics on Apache CassandraBI, Reporting and Analytics on Apache Cassandra
BI, Reporting and Analytics on Apache Cassandra
Victor Coustenoble
 
Apache Kylin
Apache KylinApache Kylin
Apache Kylin
BYOUNG GON KIM
 
PostgreSQL 15 and its Major Features -(Aakash M - Mydbops) - Mydbops Opensour...
PostgreSQL 15 and its Major Features -(Aakash M - Mydbops) - Mydbops Opensour...PostgreSQL 15 and its Major Features -(Aakash M - Mydbops) - Mydbops Opensour...
PostgreSQL 15 and its Major Features -(Aakash M - Mydbops) - Mydbops Opensour...
Mydbops
 
Oracle Database Appliance Workshop
Oracle Database Appliance WorkshopOracle Database Appliance Workshop
Oracle Database Appliance Workshop
MarketingArrowECS_CZ
 
Database storage engines
Database storage enginesDatabase storage engines
Database storage engines
University of Sindh, Jamshoro
 
Reshape Data Lake (as of 2020.07)
Reshape Data Lake (as of 2020.07)Reshape Data Lake (as of 2020.07)
Reshape Data Lake (as of 2020.07)
Eric Sun
 

What's hot (20)

Optimising Geospatial Queries with Dynamic File Pruning
Optimising Geospatial Queries with Dynamic File PruningOptimising Geospatial Queries with Dynamic File Pruning
Optimising Geospatial Queries with Dynamic File Pruning
 
Presentation upgrade, migrate & consolidate to oracle database 12c &amp...
Presentation   upgrade, migrate & consolidate to oracle database 12c &amp...Presentation   upgrade, migrate & consolidate to oracle database 12c &amp...
Presentation upgrade, migrate & consolidate to oracle database 12c &amp...
 
EM12c: Capacity Planning with OEM Metrics
EM12c: Capacity Planning with OEM MetricsEM12c: Capacity Planning with OEM Metrics
EM12c: Capacity Planning with OEM Metrics
 
Performance Stability, Tips and Tricks and Underscores
Performance Stability, Tips and Tricks and UnderscoresPerformance Stability, Tips and Tricks and Underscores
Performance Stability, Tips and Tricks and Underscores
 
Designing Apache Hudi for Incremental Processing With Vinoth Chandar and Etha...
Designing Apache Hudi for Incremental Processing With Vinoth Chandar and Etha...Designing Apache Hudi for Incremental Processing With Vinoth Chandar and Etha...
Designing Apache Hudi for Incremental Processing With Vinoth Chandar and Etha...
 
Part1 of SQL Tuning Workshop - Understanding the Optimizer
Part1 of SQL Tuning Workshop - Understanding the OptimizerPart1 of SQL Tuning Workshop - Understanding the Optimizer
Part1 of SQL Tuning Workshop - Understanding the Optimizer
 
MariaDB 마이그레이션 - 네오클로바
MariaDB 마이그레이션 - 네오클로바MariaDB 마이그레이션 - 네오클로바
MariaDB 마이그레이션 - 네오클로바
 
Introduction to Greenplum
Introduction to GreenplumIntroduction to Greenplum
Introduction to Greenplum
 
MySQL Administrator 2021 - 네오클로바
MySQL Administrator 2021 - 네오클로바MySQL Administrator 2021 - 네오클로바
MySQL Administrator 2021 - 네오클로바
 
Understanding my database through SQL*Plus using the free tool eDB360
Understanding my database through SQL*Plus using the free tool eDB360Understanding my database through SQL*Plus using the free tool eDB360
Understanding my database through SQL*Plus using the free tool eDB360
 
Linux tuning to improve PostgreSQL performance
Linux tuning to improve PostgreSQL performanceLinux tuning to improve PostgreSQL performance
Linux tuning to improve PostgreSQL performance
 
Datastage Introduction To Data Warehousing
Datastage Introduction To Data WarehousingDatastage Introduction To Data Warehousing
Datastage Introduction To Data Warehousing
 
Oracle RAC 19c: Best Practices and Secret Internals
Oracle RAC 19c: Best Practices and Secret InternalsOracle RAC 19c: Best Practices and Secret Internals
Oracle RAC 19c: Best Practices and Secret Internals
 
YugabyteDB - Distributed SQL Database on Kubernetes
YugabyteDB - Distributed SQL Database on KubernetesYugabyteDB - Distributed SQL Database on Kubernetes
YugabyteDB - Distributed SQL Database on Kubernetes
 
BI, Reporting and Analytics on Apache Cassandra
BI, Reporting and Analytics on Apache CassandraBI, Reporting and Analytics on Apache Cassandra
BI, Reporting and Analytics on Apache Cassandra
 
Apache Kylin
Apache KylinApache Kylin
Apache Kylin
 
PostgreSQL 15 and its Major Features -(Aakash M - Mydbops) - Mydbops Opensour...
PostgreSQL 15 and its Major Features -(Aakash M - Mydbops) - Mydbops Opensour...PostgreSQL 15 and its Major Features -(Aakash M - Mydbops) - Mydbops Opensour...
PostgreSQL 15 and its Major Features -(Aakash M - Mydbops) - Mydbops Opensour...
 
Oracle Database Appliance Workshop
Oracle Database Appliance WorkshopOracle Database Appliance Workshop
Oracle Database Appliance Workshop
 
Database storage engines
Database storage enginesDatabase storage engines
Database storage engines
 
Reshape Data Lake (as of 2020.07)
Reshape Data Lake (as of 2020.07)Reshape Data Lake (as of 2020.07)
Reshape Data Lake (as of 2020.07)
 

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

Jdbc oracle
Jdbc oracleJdbc oracle
Jdbc oracle
yazidds2
 
Database programming
Database programmingDatabase programming
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
Information Technology
 
Cassandra Java APIs Old and New – A Comparison
Cassandra Java APIs Old and New – A ComparisonCassandra Java APIs Old and New – A Comparison
Cassandra Java APIs Old and New – A Comparison
shsedghi
 
Python SQite3 database Tutorial | SQlite Database
Python SQite3 database Tutorial | SQlite DatabasePython SQite3 database Tutorial | SQlite Database
Python SQite3 database Tutorial | SQlite Database
ElangovanTechNotesET
 
Java OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBCJava OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBC
OUM SAOKOSAL
 
Jsp project module
Jsp project moduleJsp project module
SQL – A Tutorial I
SQL – A Tutorial  ISQL – A Tutorial  I
SQL – A Tutorial I
Gagan Deep
 
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
TAISEEREISA
 
PostgreSQL, MongoDb, Express, React, Structured
PostgreSQL, MongoDb, Express, React, StructuredPostgreSQL, MongoDb, Express, React, Structured
PostgreSQL, MongoDb, Express, React, Structured
priya951125
 
NoSQL meets Microservices - Michael Hackstein
NoSQL meets Microservices -  Michael HacksteinNoSQL meets Microservices -  Michael Hackstein
NoSQL meets Microservices - Michael Hackstein
distributed matters
 
Tutorial On Database Management System
Tutorial On Database Management SystemTutorial On Database Management System
Tutorial On Database Management System
psathishcs
 
Sql lite android
Sql lite androidSql lite android
Sql lite android
Dushyant Nasit
 
Shrug2017 arcpy data_and_you
Shrug2017 arcpy data_and_youShrug2017 arcpy data_and_you
Shrug2017 arcpy data_and_you
SHRUG GIS
 
Sqlapi0.1
Sqlapi0.1Sqlapi0.1
Sqlapi0.1
jitendral
 
Introducing Apache Spark's Data Frames and Dataset APIs workshop series
Introducing Apache Spark's Data Frames and Dataset APIs workshop seriesIntroducing Apache Spark's Data Frames and Dataset APIs workshop series
Introducing Apache Spark's Data Frames and Dataset APIs workshop series
Holden Karau
 
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
 
Jdbc ja
Jdbc jaJdbc ja
Jdbc ja
DEEPIKA T
 
Jdbc
JdbcJdbc
Jdbc
Indu Lata
 
Module 5 jdbc.ppt
Module 5   jdbc.pptModule 5   jdbc.ppt
Module 5 jdbc.ppt
MrsRLakshmiIT
 

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

Jdbc oracle
Jdbc oracleJdbc oracle
Jdbc oracle
 
Database programming
Database programmingDatabase programming
Database programming
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
 
Cassandra Java APIs Old and New – A Comparison
Cassandra Java APIs Old and New – A ComparisonCassandra Java APIs Old and New – A Comparison
Cassandra Java APIs Old and New – A Comparison
 
Python SQite3 database Tutorial | SQlite Database
Python SQite3 database Tutorial | SQlite DatabasePython SQite3 database Tutorial | SQlite Database
Python SQite3 database Tutorial | SQlite Database
 
Java OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBCJava OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBC
 
Jsp project module
Jsp project moduleJsp project module
Jsp project module
 
SQL – A Tutorial I
SQL – A Tutorial  ISQL – A Tutorial  I
SQL – A Tutorial I
 
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
 
PostgreSQL, MongoDb, Express, React, Structured
PostgreSQL, MongoDb, Express, React, StructuredPostgreSQL, MongoDb, Express, React, Structured
PostgreSQL, MongoDb, Express, React, Structured
 
NoSQL meets Microservices - Michael Hackstein
NoSQL meets Microservices -  Michael HacksteinNoSQL meets Microservices -  Michael Hackstein
NoSQL meets Microservices - Michael Hackstein
 
Tutorial On Database Management System
Tutorial On Database Management SystemTutorial On Database Management System
Tutorial On Database Management System
 
Sql lite android
Sql lite androidSql lite android
Sql lite android
 
Shrug2017 arcpy data_and_you
Shrug2017 arcpy data_and_youShrug2017 arcpy data_and_you
Shrug2017 arcpy data_and_you
 
Sqlapi0.1
Sqlapi0.1Sqlapi0.1
Sqlapi0.1
 
Introducing Apache Spark's Data Frames and Dataset APIs workshop series
Introducing Apache Spark's Data Frames and Dataset APIs workshop seriesIntroducing Apache Spark's Data Frames and Dataset APIs workshop series
Introducing Apache Spark's Data Frames and Dataset APIs workshop series
 
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
 
Jdbc ja
Jdbc jaJdbc ja
Jdbc ja
 
Jdbc
JdbcJdbc
Jdbc
 
Module 5 jdbc.ppt
Module 5   jdbc.pptModule 5   jdbc.ppt
Module 5 jdbc.ppt
 

Recently uploaded

Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
shadow0702a
 
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECTCHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
jpsjournal1
 
CEC 352 - SATELLITE COMMUNICATION UNIT 1
CEC 352 - SATELLITE COMMUNICATION UNIT 1CEC 352 - SATELLITE COMMUNICATION UNIT 1
CEC 352 - SATELLITE COMMUNICATION UNIT 1
PKavitha10
 
Introduction to AI Safety (public presentation).pptx
Introduction to AI Safety (public presentation).pptxIntroduction to AI Safety (public presentation).pptx
Introduction to AI Safety (public presentation).pptx
MiscAnnoy1
 
Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...
Prakhyath Rai
 
一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理
一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理
一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理
ecqow
 
Data Driven Maintenance | UReason Webinar
Data Driven Maintenance | UReason WebinarData Driven Maintenance | UReason Webinar
Data Driven Maintenance | UReason Webinar
UReason
 
Seminar on Distillation study-mafia.pptx
Seminar on Distillation study-mafia.pptxSeminar on Distillation study-mafia.pptx
Seminar on Distillation study-mafia.pptx
Madan Karki
 
Manufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptxManufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptx
Madan Karki
 
cnn.pptx Convolutional neural network used for image classication
cnn.pptx Convolutional neural network used for image classicationcnn.pptx Convolutional neural network used for image classication
cnn.pptx Convolutional neural network used for image classication
SakkaravarthiShanmug
 
Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...
bijceesjournal
 
The Python for beginners. This is an advance computer language.
The Python for beginners. This is an advance computer language.The Python for beginners. This is an advance computer language.
The Python for beginners. This is an advance computer language.
sachin chaurasia
 
Curve Fitting in Numerical Methods Regression
Curve Fitting in Numerical Methods RegressionCurve Fitting in Numerical Methods Regression
Curve Fitting in Numerical Methods Regression
Nada Hikmah
 
john krisinger-the science and history of the alcoholic beverage.pptx
john krisinger-the science and history of the alcoholic beverage.pptxjohn krisinger-the science and history of the alcoholic beverage.pptx
john krisinger-the science and history of the alcoholic beverage.pptx
Madan Karki
 
International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...
gerogepatton
 
Mechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdfMechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdf
21UME003TUSHARDEB
 
spirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptxspirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptx
Madan Karki
 
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
IJECEIAES
 
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student MemberIEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
VICTOR MAESTRE RAMIREZ
 
Transformers design and coooling methods
Transformers design and coooling methodsTransformers design and coooling methods
Transformers design and coooling methods
Roger Rozario
 

Recently uploaded (20)

Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
 
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECTCHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
 
CEC 352 - SATELLITE COMMUNICATION UNIT 1
CEC 352 - SATELLITE COMMUNICATION UNIT 1CEC 352 - SATELLITE COMMUNICATION UNIT 1
CEC 352 - SATELLITE COMMUNICATION UNIT 1
 
Introduction to AI Safety (public presentation).pptx
Introduction to AI Safety (public presentation).pptxIntroduction to AI Safety (public presentation).pptx
Introduction to AI Safety (public presentation).pptx
 
Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...
 
一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理
一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理
一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理
 
Data Driven Maintenance | UReason Webinar
Data Driven Maintenance | UReason WebinarData Driven Maintenance | UReason Webinar
Data Driven Maintenance | UReason Webinar
 
Seminar on Distillation study-mafia.pptx
Seminar on Distillation study-mafia.pptxSeminar on Distillation study-mafia.pptx
Seminar on Distillation study-mafia.pptx
 
Manufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptxManufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptx
 
cnn.pptx Convolutional neural network used for image classication
cnn.pptx Convolutional neural network used for image classicationcnn.pptx Convolutional neural network used for image classication
cnn.pptx Convolutional neural network used for image classication
 
Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...
 
The Python for beginners. This is an advance computer language.
The Python for beginners. This is an advance computer language.The Python for beginners. This is an advance computer language.
The Python for beginners. This is an advance computer language.
 
Curve Fitting in Numerical Methods Regression
Curve Fitting in Numerical Methods RegressionCurve Fitting in Numerical Methods Regression
Curve Fitting in Numerical Methods Regression
 
john krisinger-the science and history of the alcoholic beverage.pptx
john krisinger-the science and history of the alcoholic beverage.pptxjohn krisinger-the science and history of the alcoholic beverage.pptx
john krisinger-the science and history of the alcoholic beverage.pptx
 
International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...
 
Mechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdfMechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdf
 
spirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptxspirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptx
 
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
 
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student MemberIEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
 
Transformers design and coooling methods
Transformers design and coooling methodsTransformers design and coooling methods
Transformers design and coooling methods
 

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