SlideShare a Scribd company logo
Python database connection
Disclaimer: This presentation is prepared by trainees of
baabtra as a part of mentoring program. This is not official
document of baabtra –Mentoring Partner
Baabtra-Mentoring Partner is the mentoring division of baabte System Technologies Pvt .
Ltd
Python database connection:
Shameena v
shameenavayoli@gmail.com
www.facebook.com/shamee
navayoli
twitter.com/username
in.linkedin.com/in/shamean
9567135569
Introduction
• Psycopg2 is the most popular PostgreSql adapter
for the Python programming language
• core it fully implements the pythondb API 2.0
• Install the Psycopg2
Command for installation:
• sudo apt-get install python-psycopg2
Creating user
Here we install the psycopg2 module on a Ubuntu
system.
$ sudo -u postgres createuser janbodnar Shall the
new role be a superuser? (y/n) y
Steps:
1) We want to import psycopg2 in code
Import psycopg2
2) Connect to an existing database
conn = psycopg2.connect("dbname=test
user=postgres")
cur=conn.cursor()
3) Execute a command: this creates a new table
cur.execute("CREATE TABLE test (id serial PRIMARY
KEY, num integer, data varchar);")
• Query the database and obtain data as Python
objects
cur.execute("SELECT * FROM test;")
cur.fetchone() (1, 100, "abc'def")
4) Make the changes to the database persistent
conn.commit()
5) Close communication with the database
conn.close()
• The function connect() creates a new database
session and returns a new connection instance.
• The class connection encapsulates a database
session. It allows to:
create new cursor using the cursor()method to
execute database commands and queries,
terminate transactions using the methods
commit()or rollback()
.
• 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().
Example:
import psycopg2
try:
con=psycopg2.connect("dbname = testdb user = shafeequemonp'")
cur=con.cursor()
cur.execute('SELECT version()')
ver=cur.fetchone()
print ver
except psycopg2.DatabaseError.e:
print 'Error %s' % e
sys.exit(1)
finally:
if con:
con.close()
If this presentation helped you, please visit our
page facebook.com/baabtra and like it.
Thanks in advance.
www.baabtra.com | www.massbaab.com |www.baabte.com
Contact Us
Emarald Mall (Big Bazar Building)
Mavoor Road, Kozhikode,
Kerala, India.
Ph: + 91 – 495 40 25 550
NC Complex, Near Bus Stand
Mukkam, Kozhikode,
Kerala, India.
Ph: + 91 – 495 40 25 550
Start up Village
Eranakulam,
Kerala, India.
Email: info@baabtra.com

More Related Content

What's hot (20)

DOCX
Batch processing Demo
Peeyush Ranjan
 
PDF
Spock Testing Framework - The Next Generation
BTI360
 
PDF
Celery
Òscar Vilaplana
 
TXT
kii
suhaib khan
 
PDF
Spock Framework - Slidecast
Daniel Kolman
 
KEY
PyCon AU 2012 - Debugging Live Python Web Applications
Graham Dumpleton
 
PDF
Moo at System::Image::Update
Jens Rehsack
 
PDF
ProstgreSQLFailoverConfiguration
Suyog Shirgaonkar
 
DOC
Netw 230 Success Begins / snaptutorial.com
WilliamsTaylor65
 
PDF
Structured Testing Framework
serzar
 
PPTX
Network automation with Ansible and Python
Jisc
 
PPTX
#5 (Remote Method Invocation)
Ghadeer AlHasan
 
PDF
Chat Room System using Java Swing
Tejas Garodia
 
PPTX
Jinja Template Engine
Olalere Ridwan
 
PPTX
Code instrumentation
Bryan Reinero
 
PPTX
Group111
Shahriar Robbani
 
PDF
Use C++ to Manipulate mozSettings in Gecko
Chih-Hsuan Kuo
 
PDF
Managing PostgreSQL with PgCenter
Alexey Lesovsky
 
ODP
biopython, doctest and makefiles
Giovanni Marco Dall'Olio
 
PDF
maXbox Starter 42 Multiprocessing Programming
Max Kleiner
 
Batch processing Demo
Peeyush Ranjan
 
Spock Testing Framework - The Next Generation
BTI360
 
Spock Framework - Slidecast
Daniel Kolman
 
PyCon AU 2012 - Debugging Live Python Web Applications
Graham Dumpleton
 
Moo at System::Image::Update
Jens Rehsack
 
ProstgreSQLFailoverConfiguration
Suyog Shirgaonkar
 
Netw 230 Success Begins / snaptutorial.com
WilliamsTaylor65
 
Structured Testing Framework
serzar
 
Network automation with Ansible and Python
Jisc
 
#5 (Remote Method Invocation)
Ghadeer AlHasan
 
Chat Room System using Java Swing
Tejas Garodia
 
Jinja Template Engine
Olalere Ridwan
 
Code instrumentation
Bryan Reinero
 
Use C++ to Manipulate mozSettings in Gecko
Chih-Hsuan Kuo
 
Managing PostgreSQL with PgCenter
Alexey Lesovsky
 
biopython, doctest and makefiles
Giovanni Marco Dall'Olio
 
maXbox Starter 42 Multiprocessing Programming
Max Kleiner
 

Similar to Python database connection (20)

PDF
MobileConf 2021 Slides: Let's build macOS CLI Utilities using Swift
Diego Freniche Brito
 
PDF
Deep Learning for Computer Vision: Software Frameworks (UPC 2016)
Universitat Politècnica de Catalunya
 
PDF
Adding replication protocol support for psycopg2
Alexander Shulgin
 
PPTX
Database connectivity in python
baabtra.com - No. 1 supplier of quality freshers
 
PDF
FIWARE Tech Summit - Empower Your CKAN
FIWARE
 
PPTX
Database connectivity in python
baabtra.com - No. 1 supplier of quality freshers
 
PPTX
Psycopg2 - Connect to PostgreSQL using Python Script
Survey Department
 
PDF
Automating with NX-OS: Let's Get Started!
Cisco DevNet
 
PDF
GDG-MLOps using Protobuf in Unity
Ivan Chiou
 
PDF
Developing distributed analysis pipelines with shared community resources usi...
Brad Chapman
 
PDF
Software Frameworks for Deep Learning (D1L7 2017 UPC Deep Learning for Comput...
Universitat Politècnica de Catalunya
 
PDF
Effizientere WordPress-Plugin-Entwicklung mit Softwaretests
DECK36
 
PDF
Strategies for Puppet code upgrade and refactoring
Alessandro Franceschi
 
DOCX
Pre-Compliance Accreditation Tool for Python
Justin Dierking
 
PDF
Patterns and Tools for Database Versioning, Migration, Data Loading and Test ...
Alan Pinstein
 
PPTX
Python and Oracle : allies for best of data management
Laurent Leturgez
 
PDF
Adopt DevOps philosophy on your Symfony projects (Symfony Live 2011)
Fabrice Bernhard
 
PDF
SCons an Introduction
slantsixgames
 
PDF
The Ring programming language version 1.8 book - Part 95 of 202
Mahmoud Samir Fayed
 
PDF
Implementações paralelas
Willian Molinari
 
MobileConf 2021 Slides: Let's build macOS CLI Utilities using Swift
Diego Freniche Brito
 
Deep Learning for Computer Vision: Software Frameworks (UPC 2016)
Universitat Politècnica de Catalunya
 
Adding replication protocol support for psycopg2
Alexander Shulgin
 
Database connectivity in python
baabtra.com - No. 1 supplier of quality freshers
 
FIWARE Tech Summit - Empower Your CKAN
FIWARE
 
Database connectivity in python
baabtra.com - No. 1 supplier of quality freshers
 
Psycopg2 - Connect to PostgreSQL using Python Script
Survey Department
 
Automating with NX-OS: Let's Get Started!
Cisco DevNet
 
GDG-MLOps using Protobuf in Unity
Ivan Chiou
 
Developing distributed analysis pipelines with shared community resources usi...
Brad Chapman
 
Software Frameworks for Deep Learning (D1L7 2017 UPC Deep Learning for Comput...
Universitat Politècnica de Catalunya
 
Effizientere WordPress-Plugin-Entwicklung mit Softwaretests
DECK36
 
Strategies for Puppet code upgrade and refactoring
Alessandro Franceschi
 
Pre-Compliance Accreditation Tool for Python
Justin Dierking
 
Patterns and Tools for Database Versioning, Migration, Data Loading and Test ...
Alan Pinstein
 
Python and Oracle : allies for best of data management
Laurent Leturgez
 
Adopt DevOps philosophy on your Symfony projects (Symfony Live 2011)
Fabrice Bernhard
 
SCons an Introduction
slantsixgames
 
The Ring programming language version 1.8 book - Part 95 of 202
Mahmoud Samir Fayed
 
Implementações paralelas
Willian Molinari
 
Ad

More from baabtra.com - No. 1 supplier of quality freshers (20)

PPTX
Agile methodology and scrum development
baabtra.com - No. 1 supplier of quality freshers
 
PDF
Acquiring new skills what you should know
baabtra.com - No. 1 supplier of quality freshers
 
PDF
Baabtra.com programming at school
baabtra.com - No. 1 supplier of quality freshers
 
PDF
99LMS for Enterprises - LMS that you will love
baabtra.com - No. 1 supplier of quality freshers
 
PPTX
Chapter 6 database normalisation
baabtra.com - No. 1 supplier of quality freshers
 
PPTX
Chapter 5 transactions and dcl statements
baabtra.com - No. 1 supplier of quality freshers
 
PPTX
Chapter 4 functions, views, indexing
baabtra.com - No. 1 supplier of quality freshers
 
PPTX
Chapter 3 stored procedures
baabtra.com - No. 1 supplier of quality freshers
 
PPTX
Chapter 2 grouping,scalar and aggergate functions,joins inner join,outer join
baabtra.com - No. 1 supplier of quality freshers
 
PPTX
Chapter 1 introduction to sql server
baabtra.com - No. 1 supplier of quality freshers
 
PPTX
Chapter 1 introduction to sql server
baabtra.com - No. 1 supplier of quality freshers
 
Agile methodology and scrum development
baabtra.com - No. 1 supplier of quality freshers
 
Acquiring new skills what you should know
baabtra.com - No. 1 supplier of quality freshers
 
Baabtra.com programming at school
baabtra.com - No. 1 supplier of quality freshers
 
99LMS for Enterprises - LMS that you will love
baabtra.com - No. 1 supplier of quality freshers
 
Chapter 6 database normalisation
baabtra.com - No. 1 supplier of quality freshers
 
Chapter 5 transactions and dcl statements
baabtra.com - No. 1 supplier of quality freshers
 
Chapter 4 functions, views, indexing
baabtra.com - No. 1 supplier of quality freshers
 
Chapter 2 grouping,scalar and aggergate functions,joins inner join,outer join
baabtra.com - No. 1 supplier of quality freshers
 
Chapter 1 introduction to sql server
baabtra.com - No. 1 supplier of quality freshers
 
Chapter 1 introduction to sql server
baabtra.com - No. 1 supplier of quality freshers
 
Ad

Recently uploaded (20)

PDF
TrustArc Webinar - Navigating APAC Data Privacy Laws: Compliance & Challenges
TrustArc
 
PPTX
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
PDF
Draugnet: Anonymous Threat Reporting for a World on Fire
treyka
 
PDF
ICONIQ State of AI Report 2025 - The Builder's Playbook
Razin Mustafiz
 
PDF
Dev Dives: Accelerating agentic automation with Autopilot for Everyone
UiPathCommunity
 
PDF
Enhancing Environmental Monitoring with Real-Time Data Integration: Leveragin...
Safe Software
 
PDF
🚀 Let’s Build Our First Slack Workflow! 🔧.pdf
SanjeetMishra29
 
PDF
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
PPTX
Paycifi - Programmable Trust_Breakfast_PPTXT
FinTech Belgium
 
PDF
Kubernetes - Architecture & Components.pdf
geethak285
 
PPTX
Practical Applications of AI in Local Government
OnBoard
 
PDF
Introducing and Operating FME Flow for Kubernetes in a Large Enterprise: Expe...
Safe Software
 
PPTX
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Poster...
Michele Kryston
 
PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
PPTX
CapCut Pro PC Crack Latest Version Free Free
josanj305
 
PDF
GDG Cloud Southlake #44: Eyal Bukchin: Tightening the Kubernetes Feedback Loo...
James Anderson
 
PDF
How to Comply With Saudi Arabia’s National Cybersecurity Regulations.pdf
Bluechip Advanced Technologies
 
PDF
DoS Attack vs DDoS Attack_ The Silent Wars of the Internet.pdf
CyberPro Magazine
 
PDF
Quantum Threats Are Closer Than You Think – Act Now to Stay Secure
WSO2
 
PDF
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
TrustArc Webinar - Navigating APAC Data Privacy Laws: Compliance & Challenges
TrustArc
 
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
Draugnet: Anonymous Threat Reporting for a World on Fire
treyka
 
ICONIQ State of AI Report 2025 - The Builder's Playbook
Razin Mustafiz
 
Dev Dives: Accelerating agentic automation with Autopilot for Everyone
UiPathCommunity
 
Enhancing Environmental Monitoring with Real-Time Data Integration: Leveragin...
Safe Software
 
🚀 Let’s Build Our First Slack Workflow! 🔧.pdf
SanjeetMishra29
 
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
Paycifi - Programmable Trust_Breakfast_PPTXT
FinTech Belgium
 
Kubernetes - Architecture & Components.pdf
geethak285
 
Practical Applications of AI in Local Government
OnBoard
 
Introducing and Operating FME Flow for Kubernetes in a Large Enterprise: Expe...
Safe Software
 
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Poster...
Michele Kryston
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
CapCut Pro PC Crack Latest Version Free Free
josanj305
 
GDG Cloud Southlake #44: Eyal Bukchin: Tightening the Kubernetes Feedback Loo...
James Anderson
 
How to Comply With Saudi Arabia’s National Cybersecurity Regulations.pdf
Bluechip Advanced Technologies
 
DoS Attack vs DDoS Attack_ The Silent Wars of the Internet.pdf
CyberPro Magazine
 
Quantum Threats Are Closer Than You Think – Act Now to Stay Secure
WSO2
 
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 

Python database connection

  • 2. Disclaimer: This presentation is prepared by trainees of baabtra as a part of mentoring program. This is not official document of baabtra –Mentoring Partner Baabtra-Mentoring Partner is the mentoring division of baabte System Technologies Pvt . Ltd
  • 3. Python database connection: Shameena v [email protected] www.facebook.com/shamee navayoli twitter.com/username in.linkedin.com/in/shamean 9567135569
  • 4. Introduction • Psycopg2 is the most popular PostgreSql adapter for the Python programming language • core it fully implements the pythondb API 2.0 • Install the Psycopg2 Command for installation: • sudo apt-get install python-psycopg2 Creating user Here we install the psycopg2 module on a Ubuntu system. $ sudo -u postgres createuser janbodnar Shall the new role be a superuser? (y/n) y
  • 5. Steps: 1) We want to import psycopg2 in code Import psycopg2 2) Connect to an existing database conn = psycopg2.connect("dbname=test user=postgres") cur=conn.cursor() 3) Execute a command: this creates a new table cur.execute("CREATE TABLE test (id serial PRIMARY KEY, num integer, data varchar);")
  • 6. • Query the database and obtain data as Python objects cur.execute("SELECT * FROM test;") cur.fetchone() (1, 100, "abc'def") 4) Make the changes to the database persistent conn.commit() 5) Close communication with the database conn.close()
  • 7. • The function connect() creates a new database session and returns a new connection instance. • The class connection encapsulates a database session. It allows to: create new cursor using the cursor()method to execute database commands and queries, terminate transactions using the methods commit()or rollback()
  • 8. . • 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().
  • 9. Example: import psycopg2 try: con=psycopg2.connect("dbname = testdb user = shafeequemonp'") cur=con.cursor() cur.execute('SELECT version()') ver=cur.fetchone() print ver except psycopg2.DatabaseError.e: print 'Error %s' % e sys.exit(1) finally: if con: con.close()
  • 10. If this presentation helped you, please visit our page facebook.com/baabtra and like it. Thanks in advance. www.baabtra.com | www.massbaab.com |www.baabte.com
  • 11. Contact Us Emarald Mall (Big Bazar Building) Mavoor Road, Kozhikode, Kerala, India. Ph: + 91 – 495 40 25 550 NC Complex, Near Bus Stand Mukkam, Kozhikode, Kerala, India. Ph: + 91 – 495 40 25 550 Start up Village Eranakulam, Kerala, India. Email: [email protected]