SlideShare a Scribd company logo
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/

More Related Content

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

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
 
Psycopg2 - Connect to PostgreSQL using Python Script
Psycopg2 - Connect to PostgreSQL using Python ScriptPsycopg2 - Connect to PostgreSQL using Python Script
Psycopg2 - Connect to PostgreSQL using Python Script
Survey Department
 
Programming with Python and PostgreSQL
Programming with Python and PostgreSQLProgramming with Python and PostgreSQL
Programming with Python and PostgreSQL
Peter Eisentraut
 
Database programming
Database programmingDatabase programming
Database programming
Shree M.L.Kakadiya MCA mahila college, Amreli
 
Database Connectivity using Python and MySQL
Database Connectivity using Python and MySQLDatabase Connectivity using Python and MySQL
Database Connectivity using Python and MySQL
devsuchaye
 
Database connectivity in python
Database connectivity in pythonDatabase connectivity in python
Database connectivity in python
baabtra.com - No. 1 supplier of quality freshers
 
DATABASE CONNECTIVITY PYTHON USING MYSQL/SQLITE/POSTGRE
DATABASE CONNECTIVITY PYTHON USING MYSQL/SQLITE/POSTGREDATABASE CONNECTIVITY PYTHON USING MYSQL/SQLITE/POSTGRE
DATABASE CONNECTIVITY PYTHON USING MYSQL/SQLITE/POSTGRE
deepalishinkar1
 
Python database connection
Python database connectionPython database connection
Python database connection
baabtra.com - No. 1 supplier of quality freshers
 
Database connectivity in python
Database connectivity in pythonDatabase connectivity in python
Database connectivity in python
baabtra.com - No. 1 supplier of quality freshers
 
Python postgre sql a wonderful wedding
Python postgre sql   a wonderful weddingPython postgre sql   a wonderful wedding
Python postgre sql a wonderful wedding
Stéphane Wirtel
 
Relational Database Access with Python
Relational Database Access with PythonRelational Database Access with Python
Relational Database Access with Python
Mark Rees
 
Relational Database Access with Python ‘sans’ ORM
Relational Database Access with Python ‘sans’ ORM  Relational Database Access with Python ‘sans’ ORM
Relational Database Access with Python ‘sans’ ORM
Mark Rees
 
Databases with SQLite3.pdf
Databases with SQLite3.pdfDatabases with SQLite3.pdf
Databases with SQLite3.pdf
Deepika,Assistant Professor,PES College of Engineering ,Mandya
 
PYTHON_DATABASE_CONNECTIVITY_for_class_12.pptx
PYTHON_DATABASE_CONNECTIVITY_for_class_12.pptxPYTHON_DATABASE_CONNECTIVITY_for_class_12.pptx
PYTHON_DATABASE_CONNECTIVITY_for_class_12.pptx
HistoryScienceWorld
 
24. SQL .pdf
24. SQL .pdf24. SQL .pdf
24. SQL .pdf
Bhavya103897
 
SQL-Connectivity python for beginners easy explanation with concepts and outp...
SQL-Connectivity python for beginners easy explanation with concepts and outp...SQL-Connectivity python for beginners easy explanation with concepts and outp...
SQL-Connectivity python for beginners easy explanation with concepts and outp...
harshitagrawal2608
 
Python database access
Python database accessPython database access
Python database access
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
PythonDatabaseAPI -Presentation for Database
PythonDatabaseAPI -Presentation for DatabasePythonDatabaseAPI -Presentation for Database
PythonDatabaseAPI -Presentation for Database
dharawagh9999
 
Interface Python with MySQL.pdf
Interface Python with MySQL.pdfInterface Python with MySQL.pdf
Interface Python with MySQL.pdf
DhirajKumarBiswal
 
python db connection samples and program
python db connection samples and programpython db connection samples and program
python db connection samples and program
usha raj
 
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
 
Psycopg2 - Connect to PostgreSQL using Python Script
Psycopg2 - Connect to PostgreSQL using Python ScriptPsycopg2 - Connect to PostgreSQL using Python Script
Psycopg2 - Connect to PostgreSQL using Python Script
Survey Department
 
Programming with Python and PostgreSQL
Programming with Python and PostgreSQLProgramming with Python and PostgreSQL
Programming with Python and PostgreSQL
Peter Eisentraut
 
Database Connectivity using Python and MySQL
Database Connectivity using Python and MySQLDatabase Connectivity using Python and MySQL
Database Connectivity using Python and MySQL
devsuchaye
 
DATABASE CONNECTIVITY PYTHON USING MYSQL/SQLITE/POSTGRE
DATABASE CONNECTIVITY PYTHON USING MYSQL/SQLITE/POSTGREDATABASE CONNECTIVITY PYTHON USING MYSQL/SQLITE/POSTGRE
DATABASE CONNECTIVITY PYTHON USING MYSQL/SQLITE/POSTGRE
deepalishinkar1
 
Python postgre sql a wonderful wedding
Python postgre sql   a wonderful weddingPython postgre sql   a wonderful wedding
Python postgre sql a wonderful wedding
Stéphane Wirtel
 
Relational Database Access with Python
Relational Database Access with PythonRelational Database Access with Python
Relational Database Access with Python
Mark Rees
 
Relational Database Access with Python ‘sans’ ORM
Relational Database Access with Python ‘sans’ ORM  Relational Database Access with Python ‘sans’ ORM
Relational Database Access with Python ‘sans’ ORM
Mark Rees
 
PYTHON_DATABASE_CONNECTIVITY_for_class_12.pptx
PYTHON_DATABASE_CONNECTIVITY_for_class_12.pptxPYTHON_DATABASE_CONNECTIVITY_for_class_12.pptx
PYTHON_DATABASE_CONNECTIVITY_for_class_12.pptx
HistoryScienceWorld
 
SQL-Connectivity python for beginners easy explanation with concepts and outp...
SQL-Connectivity python for beginners easy explanation with concepts and outp...SQL-Connectivity python for beginners easy explanation with concepts and outp...
SQL-Connectivity python for beginners easy explanation with concepts and outp...
harshitagrawal2608
 
PythonDatabaseAPI -Presentation for Database
PythonDatabaseAPI -Presentation for DatabasePythonDatabaseAPI -Presentation for Database
PythonDatabaseAPI -Presentation for Database
dharawagh9999
 
Interface Python with MySQL.pdf
Interface Python with MySQL.pdfInterface Python with MySQL.pdf
Interface Python with MySQL.pdf
DhirajKumarBiswal
 
python db connection samples and program
python db connection samples and programpython db connection samples and program
python db connection samples and program
usha raj
 

Recently uploaded (20)

What are the benefits that dance brings?
What are the benefits that dance brings?What are the benefits that dance brings?
What are the benefits that dance brings?
memi27
 
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition OecdEnergy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
razelitouali
 
ROLE PLAY: FIRST AID -CPR & RECOVERY POSITION.pptx
ROLE PLAY: FIRST AID -CPR & RECOVERY POSITION.pptxROLE PLAY: FIRST AID -CPR & RECOVERY POSITION.pptx
ROLE PLAY: FIRST AID -CPR & RECOVERY POSITION.pptx
Belicia R.S
 
Overview of Off Boarding in Odoo 18 Employees
Overview of Off Boarding in Odoo 18 EmployeesOverview of Off Boarding in Odoo 18 Employees
Overview of Off Boarding in Odoo 18 Employees
Celine George
 
Sustainable Innovation with Immersive Learning
Sustainable Innovation with Immersive LearningSustainable Innovation with Immersive Learning
Sustainable Innovation with Immersive Learning
Leonel Morgado
 
LDMMIA Spring Ending Guest Grad Student News
LDMMIA Spring Ending Guest Grad Student NewsLDMMIA Spring Ending Guest Grad Student News
LDMMIA Spring Ending Guest Grad Student News
LDM & Mia eStudios
 
How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18
Celine George
 
Rai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptx
Rai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptxRai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptx
Rai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptx
Dr. Ravi Shankar Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
Paper 109 | Archetypal Journeys in ‘Interstellar’: Exploring Universal Themes...
Paper 109 | Archetypal Journeys in ‘Interstellar’: Exploring Universal Themes...Paper 109 | Archetypal Journeys in ‘Interstellar’: Exploring Universal Themes...
Paper 109 | Archetypal Journeys in ‘Interstellar’: Exploring Universal Themes...
Rajdeep Bavaliya
 
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
Revista digital preescolar en transformación
Revista digital preescolar en transformaciónRevista digital preescolar en transformación
Revista digital preescolar en transformación
guerragallardo26
 
How to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 EmployeeHow to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 Employee
Celine George
 
ABCs of Bookkeeping for Nonprofits TechSoup.pdf
ABCs of Bookkeeping for Nonprofits TechSoup.pdfABCs of Bookkeeping for Nonprofits TechSoup.pdf
ABCs of Bookkeeping for Nonprofits TechSoup.pdf
TechSoup
 
Battle of Bookworms 2025 - U25 Literature Quiz by Pragya
Battle of Bookworms 2025 - U25 Literature Quiz by Pragya Battle of Bookworms 2025 - U25 Literature Quiz by Pragya
Battle of Bookworms 2025 - U25 Literature Quiz by Pragya
Pragya - UEM Kolkata Quiz Club
 
Nice Dream.pdf /
Nice Dream.pdf                              /Nice Dream.pdf                              /
Nice Dream.pdf /
ErinUsher3
 
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdfFEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
ChristinaFortunova
 
june 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptxjune 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptx
roger malina
 
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition IILDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDM & Mia eStudios
 
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_HyderabadWebcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Veera Pallapu
 
IDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptxIDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptx
ArneeAgligar
 
What are the benefits that dance brings?
What are the benefits that dance brings?What are the benefits that dance brings?
What are the benefits that dance brings?
memi27
 
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition OecdEnergy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
razelitouali
 
ROLE PLAY: FIRST AID -CPR & RECOVERY POSITION.pptx
ROLE PLAY: FIRST AID -CPR & RECOVERY POSITION.pptxROLE PLAY: FIRST AID -CPR & RECOVERY POSITION.pptx
ROLE PLAY: FIRST AID -CPR & RECOVERY POSITION.pptx
Belicia R.S
 
Overview of Off Boarding in Odoo 18 Employees
Overview of Off Boarding in Odoo 18 EmployeesOverview of Off Boarding in Odoo 18 Employees
Overview of Off Boarding in Odoo 18 Employees
Celine George
 
Sustainable Innovation with Immersive Learning
Sustainable Innovation with Immersive LearningSustainable Innovation with Immersive Learning
Sustainable Innovation with Immersive Learning
Leonel Morgado
 
LDMMIA Spring Ending Guest Grad Student News
LDMMIA Spring Ending Guest Grad Student NewsLDMMIA Spring Ending Guest Grad Student News
LDMMIA Spring Ending Guest Grad Student News
LDM & Mia eStudios
 
How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18
Celine George
 
Paper 109 | Archetypal Journeys in ‘Interstellar’: Exploring Universal Themes...
Paper 109 | Archetypal Journeys in ‘Interstellar’: Exploring Universal Themes...Paper 109 | Archetypal Journeys in ‘Interstellar’: Exploring Universal Themes...
Paper 109 | Archetypal Journeys in ‘Interstellar’: Exploring Universal Themes...
Rajdeep Bavaliya
 
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
Revista digital preescolar en transformación
Revista digital preescolar en transformaciónRevista digital preescolar en transformación
Revista digital preescolar en transformación
guerragallardo26
 
How to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 EmployeeHow to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 Employee
Celine George
 
ABCs of Bookkeeping for Nonprofits TechSoup.pdf
ABCs of Bookkeeping for Nonprofits TechSoup.pdfABCs of Bookkeeping for Nonprofits TechSoup.pdf
ABCs of Bookkeeping for Nonprofits TechSoup.pdf
TechSoup
 
Battle of Bookworms 2025 - U25 Literature Quiz by Pragya
Battle of Bookworms 2025 - U25 Literature Quiz by Pragya Battle of Bookworms 2025 - U25 Literature Quiz by Pragya
Battle of Bookworms 2025 - U25 Literature Quiz by Pragya
Pragya - UEM Kolkata Quiz Club
 
Nice Dream.pdf /
Nice Dream.pdf                              /Nice Dream.pdf                              /
Nice Dream.pdf /
ErinUsher3
 
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdfFEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
ChristinaFortunova
 
june 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptxjune 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptx
roger malina
 
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition IILDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDM & Mia eStudios
 
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_HyderabadWebcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Veera Pallapu
 
IDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptxIDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptx
ArneeAgligar
 
Ad

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 : [email protected] Linkedin : https://www.linkedin.com/in/sachinep84/