SlideShare a Scribd company logo
7
Step 3 – Creating cursor object
• We need to create the object of a class called cursor that allows
Python code to execute database command in a database session.
• 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.
cursor = db.cursor()
• Mysql / PostgreSql
Most read
8
Step 4 -Execute SQL query
We can execute the sql queries from python program using execute() method
associated with cursor object . Examples
– cursor.execute("SELECT * from tbl_student“)
– cursor.execute("select a from tbl where b=? and c=?", x, y)
– cursor.execute("select a from tbl where b=? and c=?", (x, y))
Most read
10
Step 5 – Fetch data from database
• MySQLdb provides multiple ways to retrieve data such as:
–fetchall()
• Fetch all (remaining) rows of a query result, returning them as a sequence of
sequences (e.g. a list of tuples).
–fetchmany(size)
• Fetch the next set of rows of a query result, returning a sequence of sequences
(e.g. a list of tuples) .It will return number of rows that matches to the size
argument
–fetchone()
• Fetch the next row of a query result set, returning a single sequence,
or None when no more data is available
Most read
Introduction To Python
Python-Mysql Connectivity
Database Connectivity
• Python Database API supports a wide range of database servers:
– GadFly
– mySQL
– MySQL
– PostgreSQL
– Microsoft SQL Server 2000
– Informix
– Interbase
– Oracle
– Sybase
Step 1 – database import
• Import modules for database in your python program
Mysql
import MySQLdb
PostgreSql
import psycopg2
Step 1 – database import
• Import modules for database
Mysql
import MySQLdb
PostgreSql
import psycopg2
Traceback (most recent call last):
File "test.py", line 3, in <module>
import MySQLdb
ImportError: No module named MySQLdb
Error
If the above error happens that means
you have not installed the
mysql/postgresql module for the
python version you are using
Solution : download it from
http://sourceforge.net/projects/mysql-
python
Step 2 – Establishing connection
• Open a database connection with your program using connect()
– Mysql
– PostgreSql
db = MySQLdb.connect(user=‘root', password=‘root', host=‘localhost', database=‘test' )
db = psycopg2.connect(user=‘root', password=‘root', host=‘localhost', database=‘test' )
Step 2 – Establishing connection
• Open database connection
– Mysql
– PostgreSql
db = MySQLdb.connect(user=‘root', password=‘root', host=‘localhost', database=‘test' )
db = psycopg2.connect(user=‘root', password=‘root', host=‘localhost', database=‘test' )
the connect() constructor creates a
connection to the MySQL server and
returns a MySQLConnection object
Step 3 – Creating cursor object
• We need to create the object of a class called cursor that allows
Python code to execute database command in a database session.
• 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.
cursor = db.cursor()
• Mysql / PostgreSql
Step 4 -Execute SQL query
We can execute the sql queries from python program using execute() method
associated with cursor object . Examples
– cursor.execute("SELECT * from tbl_student“)
– cursor.execute("select a from tbl where b=? and c=?", x, y)
– cursor.execute("select a from tbl where b=? and c=?", (x, y))
Step 4 -Execute SQL query
• Executes an SQL command against all parameter sequences or
mappings found in the sequence sql
• purchases = [
('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
('2006-04-05', 'BUY', 'MSFT', 1000, 72.00),
('2006-04-06', 'SELL', 'IBM', 500, 53.00)
]
• c.executemany('INSERT INTO stocks VALUES (?,?,?,?,?)', purchases)
Step 5 – Fetch data from database
• MySQLdb provides multiple ways to retrieve data such as:
–fetchall()
• Fetch all (remaining) rows of a query result, returning them as a sequence of
sequences (e.g. a list of tuples).
–fetchmany(size)
• Fetch the next set of rows of a query result, returning a sequence of sequences
(e.g. a list of tuples) .It will return number of rows that matches to the size
argument
–fetchone()
• Fetch the next row of a query result set, returning a single sequence,
or None when no more data is available
Example
Import MySQLdb
db = MySQLdb.connect(user=‘root', password=‘root', host=‘localhost', database=‘test' )
cursor = db.cursor()
cursor.execute(“select * from tbl_student where place= calicut”)
results = cursor.fetchall()
for row in results:
fname = row[0]
lname = row[1]
age = row[2]
print "fname=%s,lname=%s,age=%d " % (fname, lname, age)
Questions?
“A good question deserve a good grade…”
Want to learn more about programming or Looking to become a good programmer?
Are you wasting time on searching so many contents online?
Do you want to learn things quickly?
Tired of spending huge amount of money to become a Software professional?
Do an online course
@ baabtra.com
We put industry standards to practice. Our structured, activity based courses are so designed
to make a quick, good software professional out of anybody who holds a passion for coding.
Follow us @ twitter.com/baabtra
Like us @ facebook.com/baabtra
Subscribe to us @ youtube.com/baabtra
Become a follower @ slideshare.net/BaabtraMentoringPartner
Connect to us @ in.linkedin.com/in/baabtra
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
Cafit Square,
Hilite Business Park,
Near Pantheerankavu,
Kozhikode
Ph:9895767088
Start up Village
Eranakulam,
Kerala, India.
Email: info@baabtra.com

More Related Content

What's hot (20)

Network programming Using Python
Network programming Using PythonNetwork programming Using Python
Network programming Using Python
Karim Sonbol
 
Functions in python
Functions in pythonFunctions in python
Functions in python
colorsof
 
Python exception handling
Python   exception handlingPython   exception handling
Python exception handling
Mohammed Sikander
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
Megha V
 
Python Pandas
Python PandasPython Pandas
Python Pandas
Sunil OS
 
File Handling Python
File Handling PythonFile Handling Python
File Handling Python
Akhil Kaushik
 
Python set
Python setPython set
Python set
Mohammed Sikander
 
Python File Handling | File Operations in Python | Learn python programming |...
Python File Handling | File Operations in Python | Learn python programming |...Python File Handling | File Operations in Python | Learn python programming |...
Python File Handling | File Operations in Python | Learn python programming |...
Edureka!
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in Python
Sujith Kumar
 
Python programming : Files
Python programming : FilesPython programming : Files
Python programming : Files
Emertxe Information Technologies Pvt Ltd
 
Python functions
Python functionsPython functions
Python functions
Prof. Dr. K. Adisesha
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
BMS Institute of Technology and Management
 
Python programming : Classes objects
Python programming : Classes objectsPython programming : Classes objects
Python programming : Classes objects
Emertxe Information Technologies Pvt Ltd
 
Python Exception Handling
Python Exception HandlingPython Exception Handling
Python Exception Handling
Megha V
 
C++ Arrays
C++ ArraysC++ Arrays
C++ Arrays
أحمد محمد
 
Python libraries
Python librariesPython libraries
Python libraries
Prof. Dr. K. Adisesha
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in python
TMARAGATHAM
 
List,tuple,dictionary
List,tuple,dictionaryList,tuple,dictionary
List,tuple,dictionary
nitamhaske
 
Strings in python
Strings in pythonStrings in python
Strings in python
Prabhakaran V M
 
List in Python
List in PythonList in Python
List in Python
Siddique Ibrahim
 

Viewers also liked (12)

Python database interfaces
Python database  interfacesPython database  interfaces
Python database interfaces
Mohammad Javad Beheshtian
 
Installing MySQL for Python
Installing MySQL for PythonInstalling MySQL for Python
Installing MySQL for Python
Siva Arunachalam
 
MySQL User Conference 2009: Python and MySQL
MySQL User Conference 2009: Python and MySQLMySQL User Conference 2009: Python and MySQL
MySQL User Conference 2009: Python and MySQL
Ted Leung
 
MySQL Guide for Beginners
MySQL Guide for BeginnersMySQL Guide for Beginners
MySQL Guide for Beginners
Dainis Graveris
 
MySQL for Beginners - part 1
MySQL for Beginners - part 1MySQL for Beginners - part 1
MySQL for Beginners - part 1
Ivan Zoratti
 
MySQL for beginners
MySQL for beginnersMySQL for beginners
MySQL for beginners
Saeid Zebardast
 
Relational Database Access with Python
Relational Database Access with PythonRelational Database Access with Python
Relational Database Access with Python
Mark Rees
 
Introduction to MySQL
Introduction to MySQLIntroduction to MySQL
Introduction to MySQL
Giuseppe Maxia
 
Python in the database
Python in the databasePython in the database
Python in the database
pybcn
 
Git 101 - Crash Course in Version Control using Git
Git 101 - Crash Course in Version Control using GitGit 101 - Crash Course in Version Control using Git
Git 101 - Crash Course in Version Control using Git
Geoff Hoffman
 
Introduction to Git/Github - A beginner's guide
Introduction to Git/Github - A beginner's guideIntroduction to Git/Github - A beginner's guide
Introduction to Git/Github - A beginner's guide
Rohit Arora
 
Git 101: Git and GitHub for Beginners
Git 101: Git and GitHub for Beginners Git 101: Git and GitHub for Beginners
Git 101: Git and GitHub for Beginners
HubSpot
 
Installing MySQL for Python
Installing MySQL for PythonInstalling MySQL for Python
Installing MySQL for Python
Siva Arunachalam
 
MySQL User Conference 2009: Python and MySQL
MySQL User Conference 2009: Python and MySQLMySQL User Conference 2009: Python and MySQL
MySQL User Conference 2009: Python and MySQL
Ted Leung
 
MySQL Guide for Beginners
MySQL Guide for BeginnersMySQL Guide for Beginners
MySQL Guide for Beginners
Dainis Graveris
 
MySQL for Beginners - part 1
MySQL for Beginners - part 1MySQL for Beginners - part 1
MySQL for Beginners - part 1
Ivan Zoratti
 
Relational Database Access with Python
Relational Database Access with PythonRelational Database Access with Python
Relational Database Access with Python
Mark Rees
 
Python in the database
Python in the databasePython in the database
Python in the database
pybcn
 
Git 101 - Crash Course in Version Control using Git
Git 101 - Crash Course in Version Control using GitGit 101 - Crash Course in Version Control using Git
Git 101 - Crash Course in Version Control using Git
Geoff Hoffman
 
Introduction to Git/Github - A beginner's guide
Introduction to Git/Github - A beginner's guideIntroduction to Git/Github - A beginner's guide
Introduction to Git/Github - A beginner's guide
Rohit Arora
 
Git 101: Git and GitHub for Beginners
Git 101: Git and GitHub for Beginners Git 101: Git and GitHub for Beginners
Git 101: Git and GitHub for Beginners
HubSpot
 
Ad

Similar to Database connectivity in python (20)

Database connectivity in python
Database connectivity in pythonDatabase connectivity in python
Database connectivity in python
baabtra.com - No. 1 supplier of quality freshers
 
Smart Data Conference: DL4J and DataVec
Smart Data Conference: DL4J and DataVecSmart Data Conference: DL4J and DataVec
Smart Data Conference: DL4J and DataVec
Josh Patterson
 
Unsupervised Aspect Based Sentiment Analysis at Scale
Unsupervised Aspect Based Sentiment Analysis at ScaleUnsupervised Aspect Based Sentiment Analysis at Scale
Unsupervised Aspect Based Sentiment Analysis at Scale
Aaron (Ari) Bornstein
 
Viktor Tsykunov: Azure Machine Learning Service
Viktor Tsykunov: Azure Machine Learning ServiceViktor Tsykunov: Azure Machine Learning Service
Viktor Tsykunov: Azure Machine Learning Service
Lviv Startup Club
 
Azure machine learning service
Azure machine learning serviceAzure machine learning service
Azure machine learning service
Ruth Yakubu
 
Interfacing python to mysql (11363255151).pptx
Interfacing python to mysql (11363255151).pptxInterfacing python to mysql (11363255151).pptx
Interfacing python to mysql (11363255151).pptx
cavicav231
 
PythonDatabaseAPI -Presentation for Database
PythonDatabaseAPI -Presentation for DatabasePythonDatabaseAPI -Presentation for Database
PythonDatabaseAPI -Presentation for Database
dharawagh9999
 
Database Connectivity using Python and MySQL
Database Connectivity using Python and MySQLDatabase Connectivity using Python and MySQL
Database Connectivity using Python and MySQL
devsuchaye
 
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
Laurent Leturgez
 
jdbcppt.pptx , jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt
jdbcppt.pptx , jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc pptjdbcppt.pptx , jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt
jdbcppt.pptx , jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt
Indu32
 
jdbcppt.pptx , jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt
jdbcppt.pptx , jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc pptjdbcppt.pptx , jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt
jdbcppt.pptx , jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt
Indu32
 
Data herding
Data herdingData herding
Data herding
unbracketed
 
Data herding
Data herdingData herding
Data herding
unbracketed
 
DjangoCon 2010 Scaling Disqus
DjangoCon 2010 Scaling DisqusDjangoCon 2010 Scaling Disqus
DjangoCon 2010 Scaling Disqus
zeeg
 
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)
Universitat Politècnica de Catalunya
 
Interface python with sql database.pdf
Interface python with sql database.pdfInterface python with sql database.pdf
Interface python with sql database.pdf
MohammadImran709594
 
Interface python with sql database.pdf--
Interface python with sql database.pdf--Interface python with sql database.pdf--
Interface python with sql database.pdf--
jagaspeed09
 
Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010
Michelangelo van Dam
 
MySql Interface database in sql python my.pptx
MySql Interface database in sql python my.pptxMySql Interface database in sql python my.pptx
MySql Interface database in sql python my.pptx
UshimArora
 
Jdbc oracle
Jdbc oracleJdbc oracle
Jdbc oracle
yazidds2
 
Smart Data Conference: DL4J and DataVec
Smart Data Conference: DL4J and DataVecSmart Data Conference: DL4J and DataVec
Smart Data Conference: DL4J and DataVec
Josh Patterson
 
Unsupervised Aspect Based Sentiment Analysis at Scale
Unsupervised Aspect Based Sentiment Analysis at ScaleUnsupervised Aspect Based Sentiment Analysis at Scale
Unsupervised Aspect Based Sentiment Analysis at Scale
Aaron (Ari) Bornstein
 
Viktor Tsykunov: Azure Machine Learning Service
Viktor Tsykunov: Azure Machine Learning ServiceViktor Tsykunov: Azure Machine Learning Service
Viktor Tsykunov: Azure Machine Learning Service
Lviv Startup Club
 
Azure machine learning service
Azure machine learning serviceAzure machine learning service
Azure machine learning service
Ruth Yakubu
 
Interfacing python to mysql (11363255151).pptx
Interfacing python to mysql (11363255151).pptxInterfacing python to mysql (11363255151).pptx
Interfacing python to mysql (11363255151).pptx
cavicav231
 
PythonDatabaseAPI -Presentation for Database
PythonDatabaseAPI -Presentation for DatabasePythonDatabaseAPI -Presentation for Database
PythonDatabaseAPI -Presentation for Database
dharawagh9999
 
Database Connectivity using Python and MySQL
Database Connectivity using Python and MySQLDatabase Connectivity using Python and MySQL
Database Connectivity using Python and MySQL
devsuchaye
 
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
Laurent Leturgez
 
jdbcppt.pptx , jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt
jdbcppt.pptx , jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc pptjdbcppt.pptx , jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt
jdbcppt.pptx , jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt
Indu32
 
jdbcppt.pptx , jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt
jdbcppt.pptx , jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc pptjdbcppt.pptx , jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt
jdbcppt.pptx , jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt
Indu32
 
DjangoCon 2010 Scaling Disqus
DjangoCon 2010 Scaling DisqusDjangoCon 2010 Scaling Disqus
DjangoCon 2010 Scaling Disqus
zeeg
 
Interface python with sql database.pdf
Interface python with sql database.pdfInterface python with sql database.pdf
Interface python with sql database.pdf
MohammadImran709594
 
Interface python with sql database.pdf--
Interface python with sql database.pdf--Interface python with sql database.pdf--
Interface python with sql database.pdf--
jagaspeed09
 
Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010
Michelangelo van Dam
 
MySql Interface database in sql python my.pptx
MySql Interface database in sql python my.pptxMySql Interface database in sql python my.pptx
MySql Interface database in sql python my.pptx
UshimArora
 
Jdbc oracle
Jdbc oracleJdbc oracle
Jdbc oracle
yazidds2
 
Ad

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
baabtra.com - No. 1 supplier of quality freshers
 
Best coding practices
Best coding practicesBest coding practices
Best coding practices
baabtra.com - No. 1 supplier of quality freshers
 
Core java - baabtra
Core java - baabtraCore java - baabtra
Core java - baabtra
baabtra.com - No. 1 supplier of quality freshers
 
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 - No. 1 supplier of quality freshers
 
Baabtra.com programming at school
Baabtra.com programming at schoolBaabtra.com programming at school
Baabtra.com programming at school
baabtra.com - No. 1 supplier of quality freshers
 
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
baabtra.com - No. 1 supplier of quality freshers
 
Php sessions & cookies
Php sessions & cookiesPhp sessions & cookies
Php sessions & cookies
baabtra.com - No. 1 supplier of quality freshers
 
Php database connectivity
Php database connectivityPhp database connectivity
Php database connectivity
baabtra.com - No. 1 supplier of quality freshers
 
Chapter 6 database normalisation
Chapter 6  database normalisationChapter 6  database normalisation
Chapter 6 database normalisation
baabtra.com - No. 1 supplier of quality freshers
 
Chapter 5 transactions and dcl statements
Chapter 5  transactions and dcl statementsChapter 5  transactions and dcl statements
Chapter 5 transactions and dcl statements
baabtra.com - No. 1 supplier of quality freshers
 
Chapter 4 functions, views, indexing
Chapter 4  functions, views, indexingChapter 4  functions, views, indexing
Chapter 4 functions, views, indexing
baabtra.com - No. 1 supplier of quality freshers
 
Chapter 3 stored procedures
Chapter 3 stored proceduresChapter 3 stored procedures
Chapter 3 stored procedures
baabtra.com - No. 1 supplier of quality freshers
 
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
baabtra.com - No. 1 supplier of quality freshers
 
Chapter 1 introduction to sql server
Chapter 1 introduction to sql serverChapter 1 introduction to sql server
Chapter 1 introduction to sql server
baabtra.com - No. 1 supplier of quality freshers
 
Chapter 1 introduction to sql server
Chapter 1 introduction to sql serverChapter 1 introduction to sql server
Chapter 1 introduction to sql server
baabtra.com - No. 1 supplier of quality freshers
 
Microsoft holo lens
Microsoft holo lensMicrosoft holo lens
Microsoft holo lens
baabtra.com - No. 1 supplier of quality freshers
 
Blue brain
Blue brainBlue brain
Blue brain
baabtra.com - No. 1 supplier of quality freshers
 
5g
5g5g
5g
baabtra.com - No. 1 supplier of quality freshers
 
Aptitude skills baabtra
Aptitude skills baabtraAptitude skills baabtra
Aptitude skills baabtra
baabtra.com - No. 1 supplier of quality freshers
 
Gd baabtra
Gd baabtraGd baabtra
Gd baabtra
baabtra.com - No. 1 supplier of quality freshers
 

Recently uploaded (20)

ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
Jasper Oosterveld
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean accountYour startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
Soulmaite review - Find Real AI soulmate review
Soulmaite review - Find Real AI soulmate reviewSoulmaite review - Find Real AI soulmate review
Soulmaite review - Find Real AI soulmate review
Soulmaite
 
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Safe Software
 
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOMEstablish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Anchore
 
Domino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use CasesDomino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use Cases
panagenda
 
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Impelsys Inc.
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training RoadblocksDown the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy SurveyTrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc
 
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
Edge AI and Vision Alliance
 
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdfHow Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
Rejig Digital
 
Trends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary MeekerTrends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary Meeker
Clive Dickens
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI ProfessionalOracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
VICTOR MAESTRE RAMIREZ
 
Data Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any ApplicationData Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any Application
Safe Software
 
7 Salesforce Data Cloud Best Practices.pdf
7 Salesforce Data Cloud Best Practices.pdf7 Salesforce Data Cloud Best Practices.pdf
7 Salesforce Data Cloud Best Practices.pdf
Minuscule Technologies
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
6th Power Grid Model Meetup - 21 May 2025
6th Power Grid Model Meetup - 21 May 20256th Power Grid Model Meetup - 21 May 2025
6th Power Grid Model Meetup - 21 May 2025
DanBrown980551
 
MCP vs A2A vs ACP: Choosing the Right Protocol | Bluebash
MCP vs A2A vs ACP: Choosing the Right Protocol | BluebashMCP vs A2A vs ACP: Choosing the Right Protocol | Bluebash
MCP vs A2A vs ACP: Choosing the Right Protocol | Bluebash
Bluebash
 
Improving Developer Productivity With DORA, SPACE, and DevEx
Improving Developer Productivity With DORA, SPACE, and DevExImproving Developer Productivity With DORA, SPACE, and DevEx
Improving Developer Productivity With DORA, SPACE, and DevEx
Justin Reock
 
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
Jasper Oosterveld
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean accountYour startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
Soulmaite review - Find Real AI soulmate review
Soulmaite review - Find Real AI soulmate reviewSoulmaite review - Find Real AI soulmate review
Soulmaite review - Find Real AI soulmate review
Soulmaite
 
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Safe Software
 
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOMEstablish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Anchore
 
Domino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use CasesDomino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use Cases
panagenda
 
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Impelsys Inc.
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training RoadblocksDown the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy SurveyTrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc
 
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
Edge AI and Vision Alliance
 
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdfHow Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
Rejig Digital
 
Trends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary MeekerTrends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary Meeker
Clive Dickens
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI ProfessionalOracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
VICTOR MAESTRE RAMIREZ
 
Data Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any ApplicationData Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any Application
Safe Software
 
7 Salesforce Data Cloud Best Practices.pdf
7 Salesforce Data Cloud Best Practices.pdf7 Salesforce Data Cloud Best Practices.pdf
7 Salesforce Data Cloud Best Practices.pdf
Minuscule Technologies
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
6th Power Grid Model Meetup - 21 May 2025
6th Power Grid Model Meetup - 21 May 20256th Power Grid Model Meetup - 21 May 2025
6th Power Grid Model Meetup - 21 May 2025
DanBrown980551
 
MCP vs A2A vs ACP: Choosing the Right Protocol | Bluebash
MCP vs A2A vs ACP: Choosing the Right Protocol | BluebashMCP vs A2A vs ACP: Choosing the Right Protocol | Bluebash
MCP vs A2A vs ACP: Choosing the Right Protocol | Bluebash
Bluebash
 
Improving Developer Productivity With DORA, SPACE, and DevEx
Improving Developer Productivity With DORA, SPACE, and DevExImproving Developer Productivity With DORA, SPACE, and DevEx
Improving Developer Productivity With DORA, SPACE, and DevEx
Justin Reock
 

Database connectivity in python

  • 2. Database Connectivity • Python Database API supports a wide range of database servers: – GadFly – mySQL – MySQL – PostgreSQL – Microsoft SQL Server 2000 – Informix – Interbase – Oracle – Sybase
  • 3. Step 1 – database import • Import modules for database in your python program Mysql import MySQLdb PostgreSql import psycopg2
  • 4. Step 1 – database import • Import modules for database Mysql import MySQLdb PostgreSql import psycopg2 Traceback (most recent call last): File "test.py", line 3, in <module> import MySQLdb ImportError: No module named MySQLdb Error If the above error happens that means you have not installed the mysql/postgresql module for the python version you are using Solution : download it from http://sourceforge.net/projects/mysql- python
  • 5. Step 2 – Establishing connection • Open a database connection with your program using connect() – Mysql – PostgreSql db = MySQLdb.connect(user=‘root', password=‘root', host=‘localhost', database=‘test' ) db = psycopg2.connect(user=‘root', password=‘root', host=‘localhost', database=‘test' )
  • 6. Step 2 – Establishing connection • Open database connection – Mysql – PostgreSql db = MySQLdb.connect(user=‘root', password=‘root', host=‘localhost', database=‘test' ) db = psycopg2.connect(user=‘root', password=‘root', host=‘localhost', database=‘test' ) the connect() constructor creates a connection to the MySQL server and returns a MySQLConnection object
  • 7. Step 3 – Creating cursor object • We need to create the object of a class called cursor that allows Python code to execute database command in a database session. • 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. cursor = db.cursor() • Mysql / PostgreSql
  • 8. Step 4 -Execute SQL query We can execute the sql queries from python program using execute() method associated with cursor object . Examples – cursor.execute("SELECT * from tbl_student“) – cursor.execute("select a from tbl where b=? and c=?", x, y) – cursor.execute("select a from tbl where b=? and c=?", (x, y))
  • 9. Step 4 -Execute SQL query • Executes an SQL command against all parameter sequences or mappings found in the sequence sql • purchases = [ ('2006-03-28', 'BUY', 'IBM', 1000, 45.00), ('2006-04-05', 'BUY', 'MSFT', 1000, 72.00), ('2006-04-06', 'SELL', 'IBM', 500, 53.00) ] • c.executemany('INSERT INTO stocks VALUES (?,?,?,?,?)', purchases)
  • 10. Step 5 – Fetch data from database • MySQLdb provides multiple ways to retrieve data such as: –fetchall() • Fetch all (remaining) rows of a query result, returning them as a sequence of sequences (e.g. a list of tuples). –fetchmany(size) • Fetch the next set of rows of a query result, returning a sequence of sequences (e.g. a list of tuples) .It will return number of rows that matches to the size argument –fetchone() • Fetch the next row of a query result set, returning a single sequence, or None when no more data is available
  • 11. Example Import MySQLdb db = MySQLdb.connect(user=‘root', password=‘root', host=‘localhost', database=‘test' ) cursor = db.cursor() cursor.execute(“select * from tbl_student where place= calicut”) results = cursor.fetchall() for row in results: fname = row[0] lname = row[1] age = row[2] print "fname=%s,lname=%s,age=%d " % (fname, lname, age)
  • 12. Questions? “A good question deserve a good grade…”
  • 13. Want to learn more about programming or Looking to become a good programmer? Are you wasting time on searching so many contents online? Do you want to learn things quickly? Tired of spending huge amount of money to become a Software professional? Do an online course @ baabtra.com We put industry standards to practice. Our structured, activity based courses are so designed to make a quick, good software professional out of anybody who holds a passion for coding.
  • 14. Follow us @ twitter.com/baabtra Like us @ facebook.com/baabtra Subscribe to us @ youtube.com/baabtra Become a follower @ slideshare.net/BaabtraMentoringPartner Connect to us @ in.linkedin.com/in/baabtra Thanks in advance. www.baabtra.com | www.massbaab.com |www.baabte.com
  • 15. 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 Cafit Square, Hilite Business Park, Near Pantheerankavu, Kozhikode Ph:9895767088 Start up Village Eranakulam, Kerala, India. Email: [email protected]