SlideShare a Scribd company logo
1 of 11
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

ProstgreSQLFailoverConfiguration
ProstgreSQLFailoverConfigurationProstgreSQLFailoverConfiguration
ProstgreSQLFailoverConfiguration
Suyog Shirgaonkar
 

What's hot (20)

Batch processing Demo
Batch processing DemoBatch processing Demo
Batch processing Demo
 
Spock Testing Framework - The Next Generation
Spock Testing Framework - The Next GenerationSpock Testing Framework - The Next Generation
Spock Testing Framework - The Next Generation
 
Celery
CeleryCelery
Celery
 
kii
kiikii
kii
 
Spock Framework - Slidecast
Spock Framework - SlidecastSpock Framework - Slidecast
Spock Framework - Slidecast
 
PyCon AU 2012 - Debugging Live Python Web Applications
PyCon AU 2012 - Debugging Live Python Web ApplicationsPyCon AU 2012 - Debugging Live Python Web Applications
PyCon AU 2012 - Debugging Live Python Web Applications
 
Moo at System::Image::Update
Moo at System::Image::UpdateMoo at System::Image::Update
Moo at System::Image::Update
 
ProstgreSQLFailoverConfiguration
ProstgreSQLFailoverConfigurationProstgreSQLFailoverConfiguration
ProstgreSQLFailoverConfiguration
 
Netw 230 Success Begins / snaptutorial.com
Netw 230  Success Begins / snaptutorial.comNetw 230  Success Begins / snaptutorial.com
Netw 230 Success Begins / snaptutorial.com
 
Structured Testing Framework
Structured Testing FrameworkStructured Testing Framework
Structured Testing Framework
 
Network automation with Ansible and Python
Network automation with Ansible and PythonNetwork automation with Ansible and Python
Network automation with Ansible and Python
 
#5 (Remote Method Invocation)
#5 (Remote Method Invocation)#5 (Remote Method Invocation)
#5 (Remote Method Invocation)
 
Chat Room System using Java Swing
Chat Room System using Java SwingChat Room System using Java Swing
Chat Room System using Java Swing
 
Jinja Template Engine
Jinja Template EngineJinja Template Engine
Jinja Template Engine
 
Code instrumentation
Code instrumentationCode instrumentation
Code instrumentation
 
Group111
Group111Group111
Group111
 
Use C++ to Manipulate mozSettings in Gecko
Use C++ to Manipulate mozSettings in GeckoUse C++ to Manipulate mozSettings in Gecko
Use C++ to Manipulate mozSettings in Gecko
 
Managing PostgreSQL with PgCenter
Managing PostgreSQL with PgCenterManaging PostgreSQL with PgCenter
Managing PostgreSQL with PgCenter
 
biopython, doctest and makefiles
biopython, doctest and makefilesbiopython, doctest and makefiles
biopython, doctest and makefiles
 
maXbox Starter 42 Multiprocessing Programming
maXbox Starter 42 Multiprocessing Programming maXbox Starter 42 Multiprocessing Programming
maXbox Starter 42 Multiprocessing Programming
 

Similar to Python database connection

Developing distributed analysis pipelines with shared community resources usi...
Developing distributed analysis pipelines with shared community resources usi...Developing distributed analysis pipelines with shared community resources usi...
Developing distributed analysis pipelines with shared community resources usi...
Brad Chapman
 
Pre-Compliance Accreditation Tool for Python
Pre-Compliance Accreditation Tool for PythonPre-Compliance Accreditation Tool for Python
Pre-Compliance Accreditation Tool for Python
Justin Dierking
 

Similar to Python database connection (20)

MobileConf 2021 Slides: Let's build macOS CLI Utilities using Swift
MobileConf 2021 Slides:  Let's build macOS CLI Utilities using SwiftMobileConf 2021 Slides:  Let's build macOS CLI Utilities using Swift
MobileConf 2021 Slides: Let's build macOS CLI Utilities using Swift
 
Deep Learning for Computer Vision: Software Frameworks (UPC 2016)
Deep Learning for Computer Vision: Software Frameworks (UPC 2016)Deep Learning for Computer Vision: Software Frameworks (UPC 2016)
Deep Learning for Computer Vision: Software Frameworks (UPC 2016)
 
Adding replication protocol support for psycopg2
Adding replication protocol support for psycopg2Adding replication protocol support for psycopg2
Adding replication protocol support for psycopg2
 
Database connectivity in python
Database connectivity in pythonDatabase connectivity in python
Database connectivity in python
 
FIWARE Tech Summit - Empower Your CKAN
FIWARE Tech Summit - Empower Your CKANFIWARE Tech Summit - Empower Your CKAN
FIWARE Tech Summit - Empower Your CKAN
 
Database connectivity in python
Database connectivity in pythonDatabase connectivity in python
Database connectivity in python
 
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
 
Automating with NX-OS: Let's Get Started!
Automating with NX-OS: Let's Get Started!Automating with NX-OS: Let's Get Started!
Automating with NX-OS: Let's Get Started!
 
GDG-MLOps using Protobuf in Unity
GDG-MLOps using Protobuf in UnityGDG-MLOps using Protobuf in Unity
GDG-MLOps using Protobuf in Unity
 
Developing distributed analysis pipelines with shared community resources usi...
Developing distributed analysis pipelines with shared community resources usi...Developing distributed analysis pipelines with shared community resources usi...
Developing distributed analysis pipelines with shared community resources usi...
 
Software Frameworks for Deep Learning (D1L7 2017 UPC Deep Learning for Comput...
Software Frameworks for Deep Learning (D1L7 2017 UPC Deep Learning for Comput...Software Frameworks for Deep Learning (D1L7 2017 UPC Deep Learning for Comput...
Software Frameworks for Deep Learning (D1L7 2017 UPC Deep Learning for Comput...
 
Effizientere WordPress-Plugin-Entwicklung mit Softwaretests
Effizientere WordPress-Plugin-Entwicklung mit SoftwaretestsEffizientere WordPress-Plugin-Entwicklung mit Softwaretests
Effizientere WordPress-Plugin-Entwicklung mit Softwaretests
 
Strategies for Puppet code upgrade and refactoring
Strategies for Puppet code upgrade and refactoringStrategies for Puppet code upgrade and refactoring
Strategies for Puppet code upgrade and refactoring
 
Pre-Compliance Accreditation Tool for Python
Pre-Compliance Accreditation Tool for PythonPre-Compliance Accreditation Tool for Python
Pre-Compliance Accreditation Tool for Python
 
Patterns and Tools for Database Versioning, Migration, Data Loading and Test ...
Patterns and Tools for Database Versioning, Migration, Data Loading and Test ...Patterns and Tools for Database Versioning, Migration, Data Loading and Test ...
Patterns and Tools for Database Versioning, Migration, Data Loading and Test ...
 
Python and Oracle : allies for best of data management
Python and Oracle : allies for best of data managementPython and Oracle : allies for best of data management
Python and Oracle : allies for best of data management
 
Adopt DevOps philosophy on your Symfony projects (Symfony Live 2011)
Adopt DevOps philosophy on your Symfony projects (Symfony Live 2011)Adopt DevOps philosophy on your Symfony projects (Symfony Live 2011)
Adopt DevOps philosophy on your Symfony projects (Symfony Live 2011)
 
SCons an Introduction
SCons an IntroductionSCons an Introduction
SCons an Introduction
 
The Ring programming language version 1.8 book - Part 95 of 202
The Ring programming language version 1.8 book - Part 95 of 202The Ring programming language version 1.8 book - Part 95 of 202
The Ring programming language version 1.8 book - Part 95 of 202
 
Implementações paralelas
Implementações paralelasImplementações paralelas
Implementações paralelas
 

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

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

Agile methodology and scrum development
Agile methodology and scrum developmentAgile methodology and scrum development
Agile methodology and scrum development
 
Best coding practices
Best coding practicesBest coding practices
Best coding practices
 
Core java - baabtra
Core java - baabtraCore java - baabtra
Core java - baabtra
 
Acquiring new skills what you should know
Acquiring new skills   what you should knowAcquiring new skills   what you should know
Acquiring new skills what you should know
 
Baabtra.com programming at school
Baabtra.com programming at schoolBaabtra.com programming at school
Baabtra.com programming at school
 
99LMS for Enterprises - LMS that you will love
99LMS for Enterprises - LMS that you will love 99LMS for Enterprises - LMS that you will love
99LMS for Enterprises - LMS that you will love
 
Php sessions & cookies
Php sessions & cookiesPhp sessions & cookies
Php sessions & cookies
 
Php database connectivity
Php database connectivityPhp database connectivity
Php database connectivity
 
Chapter 6 database normalisation
Chapter 6  database normalisationChapter 6  database normalisation
Chapter 6 database normalisation
 
Chapter 5 transactions and dcl statements
Chapter 5  transactions and dcl statementsChapter 5  transactions and dcl statements
Chapter 5 transactions and dcl statements
 
Chapter 4 functions, views, indexing
Chapter 4  functions, views, indexingChapter 4  functions, views, indexing
Chapter 4 functions, views, indexing
 
Chapter 3 stored procedures
Chapter 3 stored proceduresChapter 3 stored procedures
Chapter 3 stored procedures
 
Chapter 2 grouping,scalar and aggergate functions,joins inner join,outer join
Chapter 2  grouping,scalar and aggergate functions,joins   inner join,outer joinChapter 2  grouping,scalar and aggergate functions,joins   inner join,outer join
Chapter 2 grouping,scalar and aggergate functions,joins inner join,outer join
 
Chapter 1 introduction to sql server
Chapter 1 introduction to sql serverChapter 1 introduction to sql server
Chapter 1 introduction to sql server
 
Chapter 1 introduction to sql server
Chapter 1 introduction to sql serverChapter 1 introduction to sql server
Chapter 1 introduction to sql server
 
Microsoft holo lens
Microsoft holo lensMicrosoft holo lens
Microsoft holo lens
 
Blue brain
Blue brainBlue brain
Blue brain
 
5g
5g5g
5g
 
Aptitude skills baabtra
Aptitude skills baabtraAptitude skills baabtra
Aptitude skills baabtra
 
Gd baabtra
Gd baabtraGd baabtra
Gd baabtra
 

Recently uploaded

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 

Recently uploaded (20)

The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 

Python database connection

  • 1.
  • 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 shameenavayoli@gmail.com 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: info@baabtra.com