SlideShare ist ein Scribd-Unternehmen logo
1 von 18
PostgreSQL Python
1. psycopg2-binary : PostgreSQL Adaptor
2.DDL Operations
3.DML Operations
Installation
 pip install psycopg2-binary
 pip3 install psycopg2-binary
Python Connectors
Python
Application
pymongo
sqlite3
mySQL
pyscopg2
Python Module/Connector
Python DB API’s
Request
Response
Steps
1) Create Connection string
2) Open connection
3) Open cursor
4) Execute cursor
5) Close Cursor
6) Close Connection
Connection
Connection class
 Handles connection to database instances
 Encapsulates a database session
Connection String Example
psycopg2.connect(database="sample",user="postgres",password="sample",
host="127.0.0.1", port="5432")
connection.cursor( )
creates a cursor which will be used throughout of your database programming
with Python
Connection Method ( )
connection.commit ( )
 Commits the current transaction
 Changes will not reflect to other connections if not commited
 Default, psycopg opens a transaction before executing the first command
connection.rollback( )
 This method rolls back any changes to the database since the last call to
commit( )
connection.close( )
 This Method closes the database connection.
 If you close your database connection without calling commit() first, your
changes will
be lost!
CURSOR
 Cursor is Class
 Allows Python code to execute PostgreSQL
command in a database session
 Created by
 connection.cursor( ) Method
 cursor.execute( ), cursor.fetch( ),cursor.close( )
Execute( )
cursor.execute (query [, optional parameters])
 Execute a database operation (query or command)
returns None.
 Cursor.execute(“select * from test”)
 The returned values can be retrieved using fetch*( )
methods
cursor.executemany(query, vars_list)
 Execute a database operation (query or command)
against all parameter tuples or mappings found in
the sequence vars_list
Call Procedures
 cursor.callproc(procname[, parameters])
- Call database stored procedure
- The sequence of parameters must contain one entry for
each argument that the procedure expects
- Overloaded procedure supported
- The procedure may provide a result set as output.
- This is then made available through the standard fetch*()
methods
Fetch()
 cursor.fetchone( )
- Fetch the next row of a query result set, returning a single tuple
 cursor.fetchall( )
- This routine fetches all (remaining) rows of a query result, returning a
list. An empty list is returned when no rows are available.
 cursor.fetchmany([size=cursor.arraysize])
- Fetch the next set of rows of a query result, returning a list of
tuples.An empty list is returned when no more rows are available.
Cursor.*
Cursor.rowcount
This read-only attribute which returns the total number of database rows that
have been modified, inserted, or deleted by the last last execute*().
Cursor.query
Returns last executed query
DDL/DML OPERATIONS
-- Create Table
-- Drop Table
-- Insert Record
-- Update Record
-- Select Record
-- Delete Record
List Database
#Import library
import psycopg2
#Open Connection
conn = psycopg2.connect(database="postgres",
user='postgres', password='postgres',
host='127.0.0.1', port= '5432')
#Open cursor
cursor = conn.cursor()
#Execute Cursor
cursor.execute("select datname from
Select
import psycopg2
conn = psycopg2.connect(database = "postgres",
user = "postgres", password = "postgres", host =
"127.0.0.1", port = "5432")
cursor = conn.cursor()
cursor.execute("select * from test2")
data = cursor.fetchone()
cursor.execute("select * from test2")
data = cursor.fetchmany(2)
Create Table
import psycopg2
conn = psycopg2.connect(database =
"postgres", user = "postgres", password =
"postgres", host = "127.0.0.1", port =
"5432")
print ("Opened database successfully")
cur = conn.cursor()
cur.execute('''CREATE TABLE COMPS
(ID INT PRIMARY KEY NOT NULL,
Insert
#CREATE TABLE
- cursor.execute("CREATE TABLE test (id serial PRIMARY KEY, num integer,
data varchar(99));")
- conn.commit
#INSERT/UPDATE RECORD
cursor.execute("INSERT INTO test (num, data) VALUES (%s, %s)",(100,
"sqlnosql.com"))
conn.commit
#UPDATE
cursor.execute("UPDATE test2 set num = 999 where ID = 4")
conn.commit
cursor.rowcount
Python file
Write code in python file
Vi a.py
#Execute
python3 a.py
Contact
Website: www.sqlnosql.com
Email : sachinep84@gmail.com
Linkedin : https://www.linkedin.com/in/sachinep84/

Weitere ähnliche Inhalte

Was ist angesagt?

The View - Lotusscript coding best practices
The View - Lotusscript coding best practicesThe View - Lotusscript coding best practices
The View - Lotusscript coding best practicesBill Buchan
 
Zabbix Performance Tuning
Zabbix Performance TuningZabbix Performance Tuning
Zabbix Performance TuningRicardo Santos
 
A Hacker's perspective on AEM applications security
A Hacker's perspective on AEM applications securityA Hacker's perspective on AEM applications security
A Hacker's perspective on AEM applications securityMikhail Egorov
 
Going Beyond Microsoft IIS Short File Name Disclosure - NahamCon 2023 Edition
Going Beyond Microsoft IIS Short File Name Disclosure - NahamCon 2023 EditionGoing Beyond Microsoft IIS Short File Name Disclosure - NahamCon 2023 Edition
Going Beyond Microsoft IIS Short File Name Disclosure - NahamCon 2023 EditionSoroush Dalili
 
Presentation on samba server
Presentation on samba serverPresentation on samba server
Presentation on samba serverVeeral Bhateja
 
Scylla Summit 2022: ScyllaDB Rust Driver: One Driver to Rule Them All
Scylla Summit 2022: ScyllaDB Rust Driver: One Driver to Rule Them AllScylla Summit 2022: ScyllaDB Rust Driver: One Driver to Rule Them All
Scylla Summit 2022: ScyllaDB Rust Driver: One Driver to Rule Them AllScyllaDB
 
What’s wrong with WebSocket APIs? Unveiling vulnerabilities in WebSocket APIs.
What’s wrong with WebSocket APIs? Unveiling vulnerabilities in WebSocket APIs.What’s wrong with WebSocket APIs? Unveiling vulnerabilities in WebSocket APIs.
What’s wrong with WebSocket APIs? Unveiling vulnerabilities in WebSocket APIs.Mikhail Egorov
 
Play with FILE Structure - Yet Another Binary Exploit Technique
Play with FILE Structure - Yet Another Binary Exploit TechniquePlay with FILE Structure - Yet Another Binary Exploit Technique
Play with FILE Structure - Yet Another Binary Exploit TechniqueAngel Boy
 
[NDC17] Kubernetes로 개발서버 간단히 찍어내기
[NDC17] Kubernetes로 개발서버 간단히 찍어내기[NDC17] Kubernetes로 개발서버 간단히 찍어내기
[NDC17] Kubernetes로 개발서버 간단히 찍어내기SeungYong Oh
 
[발표자료] 오픈소스 Pacemaker 활용한 zabbix 이중화 방안(w/ Zabbix Korea Community)
[발표자료] 오픈소스 Pacemaker 활용한 zabbix 이중화 방안(w/ Zabbix Korea Community) [발표자료] 오픈소스 Pacemaker 활용한 zabbix 이중화 방안(w/ Zabbix Korea Community)
[발표자료] 오픈소스 Pacemaker 활용한 zabbix 이중화 방안(w/ Zabbix Korea Community) 동현 김
 
Fundamentals of Linux Privilege Escalation
Fundamentals of Linux Privilege EscalationFundamentals of Linux Privilege Escalation
Fundamentals of Linux Privilege Escalationnullthreat
 
Monitoramento Enterprise com Zabbix+RHEL
Monitoramento Enterprise com Zabbix+RHELMonitoramento Enterprise com Zabbix+RHEL
Monitoramento Enterprise com Zabbix+RHELAlessandro Silva
 

Was ist angesagt? (20)

The View - Lotusscript coding best practices
The View - Lotusscript coding best practicesThe View - Lotusscript coding best practices
The View - Lotusscript coding best practices
 
Zabbix Performance Tuning
Zabbix Performance TuningZabbix Performance Tuning
Zabbix Performance Tuning
 
Hack like a pro with burp suite - nullhyd
Hack like a pro with burp suite - nullhydHack like a pro with burp suite - nullhyd
Hack like a pro with burp suite - nullhyd
 
A Hacker's perspective on AEM applications security
A Hacker's perspective on AEM applications securityA Hacker's perspective on AEM applications security
A Hacker's perspective on AEM applications security
 
Dns tunnelling its all in the name
Dns tunnelling its all in the nameDns tunnelling its all in the name
Dns tunnelling its all in the name
 
#Acunetix #product #presentation
#Acunetix #product #presentation#Acunetix #product #presentation
#Acunetix #product #presentation
 
Yaml
YamlYaml
Yaml
 
Going Beyond Microsoft IIS Short File Name Disclosure - NahamCon 2023 Edition
Going Beyond Microsoft IIS Short File Name Disclosure - NahamCon 2023 EditionGoing Beyond Microsoft IIS Short File Name Disclosure - NahamCon 2023 Edition
Going Beyond Microsoft IIS Short File Name Disclosure - NahamCon 2023 Edition
 
Presentation on samba server
Presentation on samba serverPresentation on samba server
Presentation on samba server
 
Network automation (NetDevOps) with Ansible
Network automation (NetDevOps) with AnsibleNetwork automation (NetDevOps) with Ansible
Network automation (NetDevOps) with Ansible
 
Scylla Summit 2022: ScyllaDB Rust Driver: One Driver to Rule Them All
Scylla Summit 2022: ScyllaDB Rust Driver: One Driver to Rule Them AllScylla Summit 2022: ScyllaDB Rust Driver: One Driver to Rule Them All
Scylla Summit 2022: ScyllaDB Rust Driver: One Driver to Rule Them All
 
Burp suite
Burp suiteBurp suite
Burp suite
 
What’s wrong with WebSocket APIs? Unveiling vulnerabilities in WebSocket APIs.
What’s wrong with WebSocket APIs? Unveiling vulnerabilities in WebSocket APIs.What’s wrong with WebSocket APIs? Unveiling vulnerabilities in WebSocket APIs.
What’s wrong with WebSocket APIs? Unveiling vulnerabilities in WebSocket APIs.
 
Play with FILE Structure - Yet Another Binary Exploit Technique
Play with FILE Structure - Yet Another Binary Exploit TechniquePlay with FILE Structure - Yet Another Binary Exploit Technique
Play with FILE Structure - Yet Another Binary Exploit Technique
 
Windows 2019
Windows 2019Windows 2019
Windows 2019
 
[NDC17] Kubernetes로 개발서버 간단히 찍어내기
[NDC17] Kubernetes로 개발서버 간단히 찍어내기[NDC17] Kubernetes로 개발서버 간단히 찍어내기
[NDC17] Kubernetes로 개발서버 간단히 찍어내기
 
[발표자료] 오픈소스 Pacemaker 활용한 zabbix 이중화 방안(w/ Zabbix Korea Community)
[발표자료] 오픈소스 Pacemaker 활용한 zabbix 이중화 방안(w/ Zabbix Korea Community) [발표자료] 오픈소스 Pacemaker 활용한 zabbix 이중화 방안(w/ Zabbix Korea Community)
[발표자료] 오픈소스 Pacemaker 활용한 zabbix 이중화 방안(w/ Zabbix Korea Community)
 
Fundamentals of Linux Privilege Escalation
Fundamentals of Linux Privilege EscalationFundamentals of Linux Privilege Escalation
Fundamentals of Linux Privilege Escalation
 
Chromium vs. Firefox
Chromium vs. FirefoxChromium vs. Firefox
Chromium vs. Firefox
 
Monitoramento Enterprise com Zabbix+RHEL
Monitoramento Enterprise com Zabbix+RHELMonitoramento Enterprise com Zabbix+RHEL
Monitoramento Enterprise com Zabbix+RHEL
 

Ähnlich wie Psycopg2 postgres python DDL Operaytions (select , Insert , update, create table)

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 ScriptSurvey Department
 
interface with mysql.pptx
interface with mysql.pptxinterface with mysql.pptx
interface with mysql.pptxKRITIKAOJHA11
 
Using-Python-Libraries.9485146.powerpoint.pptx
Using-Python-Libraries.9485146.powerpoint.pptxUsing-Python-Libraries.9485146.powerpoint.pptx
Using-Python-Libraries.9485146.powerpoint.pptxUadAccount
 
Connecting and using PostgreSQL database with psycopg2 [Python 2.7]
Connecting and using PostgreSQL database with psycopg2 [Python 2.7]Connecting and using PostgreSQL database with psycopg2 [Python 2.7]
Connecting and using PostgreSQL database with psycopg2 [Python 2.7]Dinesh Neupane
 
The Ring programming language version 1.7 book - Part 30 of 196
The Ring programming language version 1.7 book - Part 30 of 196The Ring programming language version 1.7 book - Part 30 of 196
The Ring programming language version 1.7 book - Part 30 of 196Mahmoud Samir Fayed
 
Writing Domain-Specific Languages for BeepBeep
Writing Domain-Specific Languages for BeepBeepWriting Domain-Specific Languages for BeepBeep
Writing Domain-Specific Languages for BeepBeepSylvain Hallé
 
The Ring programming language version 1.10 book - Part 35 of 212
The Ring programming language version 1.10 book - Part 35 of 212The Ring programming language version 1.10 book - Part 35 of 212
The Ring programming language version 1.10 book - Part 35 of 212Mahmoud Samir Fayed
 
The Ring programming language version 1.4.1 book - Part 7 of 31
The Ring programming language version 1.4.1 book - Part 7 of 31The Ring programming language version 1.4.1 book - Part 7 of 31
The Ring programming language version 1.4.1 book - Part 7 of 31Mahmoud Samir Fayed
 
Python SQite3 database Tutorial | SQlite Database
Python SQite3 database Tutorial | SQlite DatabasePython SQite3 database Tutorial | SQlite Database
Python SQite3 database Tutorial | SQlite DatabaseElangovanTechNotesET
 
For this lab, you will write the following filesAbstractDataCalc.pdf
For this lab, you will write the following filesAbstractDataCalc.pdfFor this lab, you will write the following filesAbstractDataCalc.pdf
For this lab, you will write the following filesAbstractDataCalc.pdfalokindustries1
 
Processing large-scale graphs with Google(TM) Pregel by MICHAEL HACKSTEIN at...
 Processing large-scale graphs with Google(TM) Pregel by MICHAEL HACKSTEIN at... Processing large-scale graphs with Google(TM) Pregel by MICHAEL HACKSTEIN at...
Processing large-scale graphs with Google(TM) Pregel by MICHAEL HACKSTEIN at...Big Data Spain
 

Ähnlich wie Psycopg2 postgres python DDL Operaytions (select , Insert , update, create table) (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
 
Database programming
Database programmingDatabase programming
Database programming
 
Java 1-contd
Java 1-contdJava 1-contd
Java 1-contd
 
Databases with SQLite3.pdf
Databases with SQLite3.pdfDatabases with SQLite3.pdf
Databases with SQLite3.pdf
 
24. SQL .pdf
24. SQL .pdf24. SQL .pdf
24. SQL .pdf
 
Python session 10
Python session 10Python session 10
Python session 10
 
interface with mysql.pptx
interface with mysql.pptxinterface with mysql.pptx
interface with mysql.pptx
 
3 database-jdbc(1)
3 database-jdbc(1)3 database-jdbc(1)
3 database-jdbc(1)
 
Using-Python-Libraries.9485146.powerpoint.pptx
Using-Python-Libraries.9485146.powerpoint.pptxUsing-Python-Libraries.9485146.powerpoint.pptx
Using-Python-Libraries.9485146.powerpoint.pptx
 
Connecting and using PostgreSQL database with psycopg2 [Python 2.7]
Connecting and using PostgreSQL database with psycopg2 [Python 2.7]Connecting and using PostgreSQL database with psycopg2 [Python 2.7]
Connecting and using PostgreSQL database with psycopg2 [Python 2.7]
 
Functional Programming
Functional ProgrammingFunctional Programming
Functional Programming
 
The Ring programming language version 1.7 book - Part 30 of 196
The Ring programming language version 1.7 book - Part 30 of 196The Ring programming language version 1.7 book - Part 30 of 196
The Ring programming language version 1.7 book - Part 30 of 196
 
Writing Domain-Specific Languages for BeepBeep
Writing Domain-Specific Languages for BeepBeepWriting Domain-Specific Languages for BeepBeep
Writing Domain-Specific Languages for BeepBeep
 
Database connectivity in python
Database connectivity in pythonDatabase connectivity in python
Database connectivity in python
 
The Ring programming language version 1.10 book - Part 35 of 212
The Ring programming language version 1.10 book - Part 35 of 212The Ring programming language version 1.10 book - Part 35 of 212
The Ring programming language version 1.10 book - Part 35 of 212
 
The Ring programming language version 1.4.1 book - Part 7 of 31
The Ring programming language version 1.4.1 book - Part 7 of 31The Ring programming language version 1.4.1 book - Part 7 of 31
The Ring programming language version 1.4.1 book - Part 7 of 31
 
Python SQite3 database Tutorial | SQlite Database
Python SQite3 database Tutorial | SQlite DatabasePython SQite3 database Tutorial | SQlite Database
Python SQite3 database Tutorial | SQlite Database
 
Python database connection
Python database connectionPython database connection
Python database connection
 
For this lab, you will write the following filesAbstractDataCalc.pdf
For this lab, you will write the following filesAbstractDataCalc.pdfFor this lab, you will write the following filesAbstractDataCalc.pdf
For this lab, you will write the following filesAbstractDataCalc.pdf
 
Processing large-scale graphs with Google(TM) Pregel by MICHAEL HACKSTEIN at...
 Processing large-scale graphs with Google(TM) Pregel by MICHAEL HACKSTEIN at... Processing large-scale graphs with Google(TM) Pregel by MICHAEL HACKSTEIN at...
Processing large-scale graphs with Google(TM) Pregel by MICHAEL HACKSTEIN at...
 

Kürzlich hochgeladen

Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 

Kürzlich hochgeladen (20)

Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 

Psycopg2 postgres python DDL Operaytions (select , Insert , update, create table)

  • 1. PostgreSQL Python 1. psycopg2-binary : PostgreSQL Adaptor 2.DDL Operations 3.DML Operations
  • 2. Installation  pip install psycopg2-binary  pip3 install psycopg2-binary
  • 4. Steps 1) Create Connection string 2) Open connection 3) Open cursor 4) Execute cursor 5) Close Cursor 6) Close Connection
  • 5. Connection Connection class  Handles connection to database instances  Encapsulates a database session Connection String Example psycopg2.connect(database="sample",user="postgres",password="sample", host="127.0.0.1", port="5432") connection.cursor( ) creates a cursor which will be used throughout of your database programming with Python
  • 6. Connection Method ( ) connection.commit ( )  Commits the current transaction  Changes will not reflect to other connections if not commited  Default, psycopg opens a transaction before executing the first command connection.rollback( )  This method rolls back any changes to the database since the last call to commit( ) connection.close( )  This Method closes the database connection.  If you close your database connection without calling commit() first, your changes will be lost!
  • 7. CURSOR  Cursor is Class  Allows Python code to execute PostgreSQL command in a database session  Created by  connection.cursor( ) Method  cursor.execute( ), cursor.fetch( ),cursor.close( )
  • 8. Execute( ) cursor.execute (query [, optional parameters])  Execute a database operation (query or command) returns None.  Cursor.execute(“select * from test”)  The returned values can be retrieved using fetch*( ) methods cursor.executemany(query, vars_list)  Execute a database operation (query or command) against all parameter tuples or mappings found in the sequence vars_list
  • 9. Call Procedures  cursor.callproc(procname[, parameters]) - Call database stored procedure - The sequence of parameters must contain one entry for each argument that the procedure expects - Overloaded procedure supported - The procedure may provide a result set as output. - This is then made available through the standard fetch*() methods
  • 10. Fetch()  cursor.fetchone( ) - Fetch the next row of a query result set, returning a single tuple  cursor.fetchall( ) - This routine fetches all (remaining) rows of a query result, returning a list. An empty list is returned when no rows are available.  cursor.fetchmany([size=cursor.arraysize]) - Fetch the next set of rows of a query result, returning a list of tuples.An empty list is returned when no more rows are available.
  • 11. Cursor.* Cursor.rowcount This read-only attribute which returns the total number of database rows that have been modified, inserted, or deleted by the last last execute*(). Cursor.query Returns last executed query
  • 12. DDL/DML OPERATIONS -- Create Table -- Drop Table -- Insert Record -- Update Record -- Select Record -- Delete Record
  • 13. List Database #Import library import psycopg2 #Open Connection conn = psycopg2.connect(database="postgres", user='postgres', password='postgres', host='127.0.0.1', port= '5432') #Open cursor cursor = conn.cursor() #Execute Cursor cursor.execute("select datname from
  • 14. Select import psycopg2 conn = psycopg2.connect(database = "postgres", user = "postgres", password = "postgres", host = "127.0.0.1", port = "5432") cursor = conn.cursor() cursor.execute("select * from test2") data = cursor.fetchone() cursor.execute("select * from test2") data = cursor.fetchmany(2)
  • 15. Create Table import psycopg2 conn = psycopg2.connect(database = "postgres", user = "postgres", password = "postgres", host = "127.0.0.1", port = "5432") print ("Opened database successfully") cur = conn.cursor() cur.execute('''CREATE TABLE COMPS (ID INT PRIMARY KEY NOT NULL,
  • 16. Insert #CREATE TABLE - cursor.execute("CREATE TABLE test (id serial PRIMARY KEY, num integer, data varchar(99));") - conn.commit #INSERT/UPDATE RECORD cursor.execute("INSERT INTO test (num, data) VALUES (%s, %s)",(100, "sqlnosql.com")) conn.commit #UPDATE cursor.execute("UPDATE test2 set num = 999 where ID = 4") conn.commit cursor.rowcount
  • 17. Python file Write code in python file Vi a.py #Execute python3 a.py
  • 18. Contact Website: www.sqlnosql.com Email : sachinep84@gmail.com Linkedin : https://www.linkedin.com/in/sachinep84/