SlideShare a Scribd company logo
1 of 22
Download to read offline
Databases in
Python
MySql, SQLite
Accessing persistent storage (Relational
databases) from Python code
Goal
• Making some data ‘persistent’
– When application restarts
– When computer restarts
• Manage big amounts of data
– Not all in-memory
• Exploit the power of SQL
– Complex data
– Complex queries
5/6/2015 Python databases 2
Python application
General Architecture
5/6/2015 Python databases 3
Flask application
Database API definition: PEP 0249
MySQL
«connector»
module
SQLite module
MySQL server SQLite library
Analyzed databases
MySQL
• Open source database
server
• Full featured
• Runs as a separate
process (may be on a
different computer)
• Allows concurrent access
• http://dev.mysql.com
SQLite
• Open source file-based
storage
• Software library
integrated in your
program (serverless)
• Self-contained
• https://www.sqlite.org/
5/6/2015 Python databases 4
Other options
• MariaDB – fork of MySQL
• PostgreSQL – more complex, but more complete
than MySQL
• Non-relational databases (‘NoSQL’)
– won’t be considered here
5/6/2015 Python databases 5
PEP 0249
• Python Database API Specification v2.0
– https://www.python.org/dev/peps/pep-0249/
• Specifies a standard API that Python modules
that are used to access databases should
implement
• Does not provide a library nor a module
• Third party modules may adhere to these
specifications
5/6/2015 Python databases 6
Main concepts in PEP 249
• Access to database is provided through a
connect method, that returns a Connection
object
• For executing queries, you need a Cursor
object, that can be obtained by the Connection
• A cursor may execute() a SQL query, with
parameters
• A cursor may fetch the results of the query
5/6/2015 Python databases 7
Minimal example
5/6/2015 Python databases 8
sql = "SELECT id, original, modified FROM translation"
conn = mysql.connector.connect(user='root', password='',
host='localhost', database='funnyecho')
cursor = conn.cursor()
cursor.execute(sql)
translations = cursor.fetchall()
cursor.close()
conn.close()
return translations
1
2
3
4
5
6
Step 1: defining the query
• Write a correct SQL statement, stored as a
Python string
– sql = "SELECT id, original, modified FROM
translation"
• Variable arguments may be specified with ‘%s’
placeholders
– sql = "INSERT INTO translation (original,
modified) VALUES (%s, %s)"
5/6/2015 Python databases 9
Step 2: Connecting to the database
• Depending on the library, use the provided
‘connect’ method
• The method parameters are dependent on the
module implementation (non-standard)
– conn = mysql.connector.connect(user='root',
password='', host='localhost',
database='funnyecho')
5/6/2015 Python databases 10
Step 5 (a): Clean up
• Don’t forget to close the connection, thus freeing
up resources on the database server
• conn.close()
• Write the close statement immediately, otherwise
you’ll forget it
• Remember not to ‘return’ the function before
cleaning up
5/6/2015 Python databases 11
Step 3: execute the query
• First, obtain a cursor from the connection
– cursor = conn.cursor()
• Then, execute the query
– cursor.execute(sql)
• Query parameters (%s placeholders) are
specified as a ‘tuple’ argument
– cursor.execute(sql, (txtbefore, txtafter) )
– cursor.execute(sql, (txtid,) )
– Beware: one-element tuples require trailing ,
5/6/2015 Python databases 12
Step 4 (SELECT): Analyze the
result
• Only if the query was a SELECT
• Use various methods of cursor:
– cursor.fetchone() # next result
– cursor.fetchall() # all remaining results
– They return tuples, corresponding to the SELECT’ed
columns
5/6/2015 Python databases 13
Step 4 (UPDATE): Commit the
change
• For INSERT, UPDATE and DELETE there is no
result
• The change is not applied immediately to the
database, but needs to be «committed»
• conn.commit()
– Will commit all pending executed queries in the
connection
• Must be called before conn.close()
• Don’t forget, or you’ll lose your data
5/6/2015 Python databases 14
Step 5 (b): Clean up
• When the cursor is no longer needed
• cursor.close()
5/6/2015 Python databases 15
Step 6: Use the results
• Analyze the returned data, and do what the
application requires for them.
• If further queries are needed, go back to step 3
(re-use the same Connection, creating new
Cursors)
5/6/2015 Python databases 16
Using MySQL
• Pre-requisite: a working installation of the mysql
server
– sudo apt-get install mysql-server
– Or download from
http://dev.mysql.com/downloads/mysql/
• Download and install the «MySQL Connector for
Python»
– http://dev.mysql.com/downloads/connector/python/
– Provides the package «mysql.connector»
5/6/2015 Python databases 17
MySQL Python Connector
• To use: import mysql.connector
• Well-done documentation at
– http://dev.mysql.com/doc/connector-
python/en/index.html
5/6/2015 Python databases 18
Connecting with mysql
• Basic form
– cnx = mysql.connector.connect(
• user='joe',
• password='xxx',
• database='test‘ )
• Additional parameters
– http://dev.mysql.com/doc/connector-
python/en/connector-python-connectargs.html
5/6/2015 Python databases 19
SQLite and Python
• SQLite is a simple file-based storage library
• Since Python 2.5, it is included by default, in the
«sqlite3» package
– https://docs.python.org/2/library/sqlite3.html
– Developed at https://github.com/ghaering/pysqlite
• The «connection» just means specifying the file
name
5/6/2015 Python databases 20
import sqlite3
conn = sqlite3.connect('example.db')
References and Links
• MySQL: http://dev.mysql.com/
• SQLite (C library): https://www.sqlite.org/
• SQLite for Python (installed by default):
– Documentation: https://docs.python.org/2/library/sqlite3.html
– Developer: https://github.com/ghaering/pysqlite
• PEP 249 «Python Database API Specification v2.0»:
https://www.python.org/dev/peps/pep-0249/
• MySQL Connector/Python (mysql.connector)
– Download & install:
http://dev.mysql.com/downloads/connector/python/
– Documentation: http://dev.mysql.com/doc/connector-
python/en/index.html
5/6/2015 Python databases 21
License
• This work is licensed under the Creative Commons “Attribution-
NonCommercial-ShareAlike Unported (CC BY-NC-SA 3,0)” License.
• You are free:
– to Share - to copy, distribute and transmit the work
– to Remix - to adapt the work
• Under the following conditions:
– Attribution - You must attribute the work in the manner specified by the
author or licensor (but not in any way that suggests that they endorse you or
your use of the work).
– Noncommercial - You may not use this work for commercial purposes.
– Share Alike - If you alter, transform, or build upon this work, you may
distribute the resulting work only under the same or similar license to this
one.
• To view a copy of this license, visit
http://creativecommons.org/license/by-nc-sa/3.0/
5/6/2015 Python databases 22

More Related Content

What's hot

Tasks of database administrator
Tasks of database administratorTasks of database administrator
Tasks of database administratorAttia Qamar
 
Mule quartz hari_gatadi
Mule quartz hari_gatadiMule quartz hari_gatadi
Mule quartz hari_gatadiHari Gatadi
 
Database Change Management as a Service
Database Change Management as a ServiceDatabase Change Management as a Service
Database Change Management as a ServiceAndrew Solomon
 
SQLite3
SQLite3SQLite3
SQLite3cltru
 
IOUG Collaborate 2015 - PDB Cloning Using SQL Commands
IOUG Collaborate 2015 - PDB Cloning Using SQL CommandsIOUG Collaborate 2015 - PDB Cloning Using SQL Commands
IOUG Collaborate 2015 - PDB Cloning Using SQL CommandsLeighton Nelson
 
Midwest PHP Presentation - New MSQL Features
Midwest PHP Presentation - New MSQL FeaturesMidwest PHP Presentation - New MSQL Features
Midwest PHP Presentation - New MSQL FeaturesDave Stokes
 
For each component in mule
For each component in muleFor each component in mule
For each component in muleRajkattamuri
 
For each component in mule demo
For each component in mule demoFor each component in mule demo
For each component in mule demoSudha Ch
 
Quartz component in mule
Quartz component in muleQuartz component in mule
Quartz component in mulejaveed_mhd
 
Looking at RAC, GI/Clusterware Diagnostic Tools
Looking at RAC,   GI/Clusterware Diagnostic Tools Looking at RAC,   GI/Clusterware Diagnostic Tools
Looking at RAC, GI/Clusterware Diagnostic Tools Leighton Nelson
 
Containerized Data Persistence on Mesos
Containerized Data Persistence on MesosContainerized Data Persistence on Mesos
Containerized Data Persistence on MesosJoe Stein
 
Batch Applications for the Java Platform
Batch Applications for the Java PlatformBatch Applications for the Java Platform
Batch Applications for the Java PlatformSivakumar Thyagarajan
 
Making Distributed Data Persistent Services Elastic (Without Losing All Your ...
Making Distributed Data Persistent Services Elastic (Without Losing All Your ...Making Distributed Data Persistent Services Elastic (Without Losing All Your ...
Making Distributed Data Persistent Services Elastic (Without Losing All Your ...Joe Stein
 
Li liq liqui liquibase
Li liq liqui liquibaseLi liq liqui liquibase
Li liq liqui liquibaseYoram Michaeli
 
How to Play at Work - A Play Framework Tutorial
How to Play at Work - A Play Framework TutorialHow to Play at Work - A Play Framework Tutorial
How to Play at Work - A Play Framework TutorialAssistSoftware
 

What's hot (20)

Tasks of database administrator
Tasks of database administratorTasks of database administrator
Tasks of database administrator
 
QN Blue Lava
QN Blue LavaQN Blue Lava
QN Blue Lava
 
Mule quartz hari_gatadi
Mule quartz hari_gatadiMule quartz hari_gatadi
Mule quartz hari_gatadi
 
Mule HDFS Connector
Mule HDFS ConnectorMule HDFS Connector
Mule HDFS Connector
 
Database Change Management as a Service
Database Change Management as a ServiceDatabase Change Management as a Service
Database Change Management as a Service
 
Identity service keystone ppt
Identity service keystone pptIdentity service keystone ppt
Identity service keystone ppt
 
SQLite 3
SQLite 3SQLite 3
SQLite 3
 
SQLite3
SQLite3SQLite3
SQLite3
 
IOUG Collaborate 2015 - PDB Cloning Using SQL Commands
IOUG Collaborate 2015 - PDB Cloning Using SQL CommandsIOUG Collaborate 2015 - PDB Cloning Using SQL Commands
IOUG Collaborate 2015 - PDB Cloning Using SQL Commands
 
Hazelcast
HazelcastHazelcast
Hazelcast
 
Midwest PHP Presentation - New MSQL Features
Midwest PHP Presentation - New MSQL FeaturesMidwest PHP Presentation - New MSQL Features
Midwest PHP Presentation - New MSQL Features
 
For each component in mule
For each component in muleFor each component in mule
For each component in mule
 
For each component in mule demo
For each component in mule demoFor each component in mule demo
For each component in mule demo
 
Quartz component in mule
Quartz component in muleQuartz component in mule
Quartz component in mule
 
Looking at RAC, GI/Clusterware Diagnostic Tools
Looking at RAC,   GI/Clusterware Diagnostic Tools Looking at RAC,   GI/Clusterware Diagnostic Tools
Looking at RAC, GI/Clusterware Diagnostic Tools
 
Containerized Data Persistence on Mesos
Containerized Data Persistence on MesosContainerized Data Persistence on Mesos
Containerized Data Persistence on Mesos
 
Batch Applications for the Java Platform
Batch Applications for the Java PlatformBatch Applications for the Java Platform
Batch Applications for the Java Platform
 
Making Distributed Data Persistent Services Elastic (Without Losing All Your ...
Making Distributed Data Persistent Services Elastic (Without Losing All Your ...Making Distributed Data Persistent Services Elastic (Without Losing All Your ...
Making Distributed Data Persistent Services Elastic (Without Losing All Your ...
 
Li liq liqui liquibase
Li liq liqui liquibaseLi liq liqui liquibase
Li liq liqui liquibase
 
How to Play at Work - A Play Framework Tutorial
How to Play at Work - A Play Framework TutorialHow to Play at Work - A Play Framework Tutorial
How to Play at Work - A Play Framework Tutorial
 

Viewers also liked

AmI 2015 - Design Process
AmI 2015 - Design ProcessAmI 2015 - Design Process
AmI 2015 - Design ProcessFulvio Corno
 
Ingegneri e disabilità: abbattere il muro
Ingegneri e disabilità: abbattere il muroIngegneri e disabilità: abbattere il muro
Ingegneri e disabilità: abbattere il muroFulvio Corno
 
Accessibilità dei siti web
Accessibilità dei siti webAccessibilità dei siti web
Accessibilità dei siti webFulvio Corno
 
Ambient Intelligence Design Process
Ambient Intelligence Design ProcessAmbient Intelligence Design Process
Ambient Intelligence Design ProcessFulvio Corno
 
Ambient Intelligence - Course Introduction
Ambient Intelligence - Course IntroductionAmbient Intelligence - Course Introduction
Ambient Intelligence - Course IntroductionFulvio Corno
 
Programming with JavaFX
Programming with JavaFXProgramming with JavaFX
Programming with JavaFXFulvio Corno
 
Gli anelli mancanti per l’Ambient Intelligence
Gli anelli mancanti per l’Ambient IntelligenceGli anelli mancanti per l’Ambient Intelligence
Gli anelli mancanti per l’Ambient IntelligenceFulvio Corno
 
A Healthcare Support System for Assisted Living Facilities: an IoT Solution
A Healthcare Support System for Assisted Living Facilities: an IoT SolutionA Healthcare Support System for Assisted Living Facilities: an IoT Solution
A Healthcare Support System for Assisted Living Facilities: an IoT SolutionFulvio Corno
 
Definition of Ambient Intelligence
Definition of Ambient IntelligenceDefinition of Ambient Intelligence
Definition of Ambient IntelligenceFulvio Corno
 
Introduzione al Corso - Tecniche di Programmazione 2015
Introduzione al Corso - Tecniche di Programmazione 2015Introduzione al Corso - Tecniche di Programmazione 2015
Introduzione al Corso - Tecniche di Programmazione 2015Fulvio Corno
 
Introduzione al Corso - Tecnologie per la Disabilità 2014/2015
Introduzione al Corso - Tecnologie per la Disabilità 2014/2015Introduzione al Corso - Tecnologie per la Disabilità 2014/2015
Introduzione al Corso - Tecnologie per la Disabilità 2014/2015Fulvio Corno
 
Dates and Times in Java 7 and Java 8
Dates and Times in Java 7 and Java 8Dates and Times in Java 7 and Java 8
Dates and Times in Java 7 and Java 8Fulvio Corno
 
Ausili: definizioni e normative - Tecnologie per la Disabilità 2014/2015
Ausili: definizioni e normative - Tecnologie per la Disabilità 2014/2015Ausili: definizioni e normative - Tecnologie per la Disabilità 2014/2015
Ausili: definizioni e normative - Tecnologie per la Disabilità 2014/2015Fulvio Corno
 
Ambient Intelligence: Theme of the Year 2016
Ambient Intelligence: Theme of the Year 2016Ambient Intelligence: Theme of the Year 2016
Ambient Intelligence: Theme of the Year 2016Fulvio Corno
 
Indicatori quantitativi per la valutazione dei processi
Indicatori quantitativi per la valutazione dei processiIndicatori quantitativi per la valutazione dei processi
Indicatori quantitativi per la valutazione dei processiFulvio Corno
 
Ambient intelligence - an overview
Ambient intelligence - an overviewAmbient intelligence - an overview
Ambient intelligence - an overviewFulvio Corno
 
Internet of Things - Cos'è e cosa ci posso fare?
Internet of Things - Cos'è e cosa ci posso fare?Internet of Things - Cos'è e cosa ci posso fare?
Internet of Things - Cos'è e cosa ci posso fare?Fulvio Corno
 

Viewers also liked (17)

AmI 2015 - Design Process
AmI 2015 - Design ProcessAmI 2015 - Design Process
AmI 2015 - Design Process
 
Ingegneri e disabilità: abbattere il muro
Ingegneri e disabilità: abbattere il muroIngegneri e disabilità: abbattere il muro
Ingegneri e disabilità: abbattere il muro
 
Accessibilità dei siti web
Accessibilità dei siti webAccessibilità dei siti web
Accessibilità dei siti web
 
Ambient Intelligence Design Process
Ambient Intelligence Design ProcessAmbient Intelligence Design Process
Ambient Intelligence Design Process
 
Ambient Intelligence - Course Introduction
Ambient Intelligence - Course IntroductionAmbient Intelligence - Course Introduction
Ambient Intelligence - Course Introduction
 
Programming with JavaFX
Programming with JavaFXProgramming with JavaFX
Programming with JavaFX
 
Gli anelli mancanti per l’Ambient Intelligence
Gli anelli mancanti per l’Ambient IntelligenceGli anelli mancanti per l’Ambient Intelligence
Gli anelli mancanti per l’Ambient Intelligence
 
A Healthcare Support System for Assisted Living Facilities: an IoT Solution
A Healthcare Support System for Assisted Living Facilities: an IoT SolutionA Healthcare Support System for Assisted Living Facilities: an IoT Solution
A Healthcare Support System for Assisted Living Facilities: an IoT Solution
 
Definition of Ambient Intelligence
Definition of Ambient IntelligenceDefinition of Ambient Intelligence
Definition of Ambient Intelligence
 
Introduzione al Corso - Tecniche di Programmazione 2015
Introduzione al Corso - Tecniche di Programmazione 2015Introduzione al Corso - Tecniche di Programmazione 2015
Introduzione al Corso - Tecniche di Programmazione 2015
 
Introduzione al Corso - Tecnologie per la Disabilità 2014/2015
Introduzione al Corso - Tecnologie per la Disabilità 2014/2015Introduzione al Corso - Tecnologie per la Disabilità 2014/2015
Introduzione al Corso - Tecnologie per la Disabilità 2014/2015
 
Dates and Times in Java 7 and Java 8
Dates and Times in Java 7 and Java 8Dates and Times in Java 7 and Java 8
Dates and Times in Java 7 and Java 8
 
Ausili: definizioni e normative - Tecnologie per la Disabilità 2014/2015
Ausili: definizioni e normative - Tecnologie per la Disabilità 2014/2015Ausili: definizioni e normative - Tecnologie per la Disabilità 2014/2015
Ausili: definizioni e normative - Tecnologie per la Disabilità 2014/2015
 
Ambient Intelligence: Theme of the Year 2016
Ambient Intelligence: Theme of the Year 2016Ambient Intelligence: Theme of the Year 2016
Ambient Intelligence: Theme of the Year 2016
 
Indicatori quantitativi per la valutazione dei processi
Indicatori quantitativi per la valutazione dei processiIndicatori quantitativi per la valutazione dei processi
Indicatori quantitativi per la valutazione dei processi
 
Ambient intelligence - an overview
Ambient intelligence - an overviewAmbient intelligence - an overview
Ambient intelligence - an overview
 
Internet of Things - Cos'è e cosa ci posso fare?
Internet of Things - Cos'è e cosa ci posso fare?Internet of Things - Cos'è e cosa ci posso fare?
Internet of Things - Cos'è e cosa ci posso fare?
 

Similar to AmI 2015 - Databases in Python

Social Connections 13 - Troubleshooting Connections Pink
Social Connections 13 - Troubleshooting Connections PinkSocial Connections 13 - Troubleshooting Connections Pink
Social Connections 13 - Troubleshooting Connections PinkNico Meisenzahl
 
MySQL for Oracle DBAs
MySQL for Oracle DBAsMySQL for Oracle DBAs
MySQL for Oracle DBAsBen Krug
 
Python - db.pptx
Python - db.pptxPython - db.pptx
Python - db.pptxRAGAVIC2
 
Making MySQL Administration a Breeze - A look into a MySQL DBA's toolchest
Making MySQL Administration a Breeze - A look into a MySQL DBA's toolchest Making MySQL Administration a Breeze - A look into a MySQL DBA's toolchest
Making MySQL Administration a Breeze - A look into a MySQL DBA's toolchest Lenz Grimmer
 
IBM Think 2018 - IBM Connections Troubleshooting
IBM Think 2018 -  IBM Connections TroubleshootingIBM Think 2018 -  IBM Connections Troubleshooting
IBM Think 2018 - IBM Connections TroubleshootingNico Meisenzahl
 
PythonDatabaseAPI -Presentation for Database
PythonDatabaseAPI -Presentation for DatabasePythonDatabaseAPI -Presentation for Database
PythonDatabaseAPI -Presentation for Databasedharawagh9999
 
Cypress.pptx
Cypress.pptxCypress.pptx
Cypress.pptxArshad QA
 
Leonid Vasilyev "Building, deploying and running production code at Dropbox"
Leonid Vasilyev  "Building, deploying and running production code at Dropbox"Leonid Vasilyev  "Building, deploying and running production code at Dropbox"
Leonid Vasilyev "Building, deploying and running production code at Dropbox"IT Event
 
2015: Whats New in MySQL 5.7, At Oracle Open World, November 3rd, 2015
2015: Whats New in MySQL 5.7, At Oracle Open World, November 3rd, 2015 2015: Whats New in MySQL 5.7, At Oracle Open World, November 3rd, 2015
2015: Whats New in MySQL 5.7, At Oracle Open World, November 3rd, 2015 Geir Høydalsvik
 
Building microservices sample application
Building microservices sample applicationBuilding microservices sample application
Building microservices sample applicationAnil Allewar
 
Servlets Java Slides & Presentation
Servlets Java Slides & Presentation Servlets Java Slides & Presentation
Servlets Java Slides & Presentation Anas Sa
 
ELK Ruminating on Logs (Zendcon 2016)
ELK Ruminating on Logs (Zendcon 2016)ELK Ruminating on Logs (Zendcon 2016)
ELK Ruminating on Logs (Zendcon 2016)Mathew Beane
 
Tungsten Webinar: v6 & v7 Release Recap, and Beyond
Tungsten Webinar: v6 & v7 Release Recap, and BeyondTungsten Webinar: v6 & v7 Release Recap, and Beyond
Tungsten Webinar: v6 & v7 Release Recap, and BeyondContinuent
 
Tuga it 2016 improving your application performance
Tuga it 2016   improving your application performanceTuga it 2016   improving your application performance
Tuga it 2016 improving your application performanceNuno Caneco
 
Geek Sync | Deployment and Management of Complex Azure Environments
Geek Sync | Deployment and Management of Complex Azure EnvironmentsGeek Sync | Deployment and Management of Complex Azure Environments
Geek Sync | Deployment and Management of Complex Azure EnvironmentsIDERA Software
 
Scylla Summit 2016: Compose on Containing the Database
Scylla Summit 2016: Compose on Containing the DatabaseScylla Summit 2016: Compose on Containing the Database
Scylla Summit 2016: Compose on Containing the DatabaseScyllaDB
 

Similar to AmI 2015 - Databases in Python (20)

Webscripts Server
Webscripts ServerWebscripts Server
Webscripts Server
 
Social Connections 13 - Troubleshooting Connections Pink
Social Connections 13 - Troubleshooting Connections PinkSocial Connections 13 - Troubleshooting Connections Pink
Social Connections 13 - Troubleshooting Connections Pink
 
MySQL for Oracle DBAs
MySQL for Oracle DBAsMySQL for Oracle DBAs
MySQL for Oracle DBAs
 
Python - db.pptx
Python - db.pptxPython - db.pptx
Python - db.pptx
 
Making MySQL Administration a Breeze - A look into a MySQL DBA's toolchest
Making MySQL Administration a Breeze - A look into a MySQL DBA's toolchest Making MySQL Administration a Breeze - A look into a MySQL DBA's toolchest
Making MySQL Administration a Breeze - A look into a MySQL DBA's toolchest
 
IBM Think 2018 - IBM Connections Troubleshooting
IBM Think 2018 -  IBM Connections TroubleshootingIBM Think 2018 -  IBM Connections Troubleshooting
IBM Think 2018 - IBM Connections Troubleshooting
 
PythonDatabaseAPI -Presentation for Database
PythonDatabaseAPI -Presentation for DatabasePythonDatabaseAPI -Presentation for Database
PythonDatabaseAPI -Presentation for Database
 
Cypress.pptx
Cypress.pptxCypress.pptx
Cypress.pptx
 
Leonid Vasilyev "Building, deploying and running production code at Dropbox"
Leonid Vasilyev  "Building, deploying and running production code at Dropbox"Leonid Vasilyev  "Building, deploying and running production code at Dropbox"
Leonid Vasilyev "Building, deploying and running production code at Dropbox"
 
2015: Whats New in MySQL 5.7, At Oracle Open World, November 3rd, 2015
2015: Whats New in MySQL 5.7, At Oracle Open World, November 3rd, 2015 2015: Whats New in MySQL 5.7, At Oracle Open World, November 3rd, 2015
2015: Whats New in MySQL 5.7, At Oracle Open World, November 3rd, 2015
 
Building microservices sample application
Building microservices sample applicationBuilding microservices sample application
Building microservices sample application
 
Perl Programming - 04 Programming Database
Perl Programming - 04 Programming DatabasePerl Programming - 04 Programming Database
Perl Programming - 04 Programming Database
 
Servlets
ServletsServlets
Servlets
 
Servlets Java Slides & Presentation
Servlets Java Slides & Presentation Servlets Java Slides & Presentation
Servlets Java Slides & Presentation
 
ELK Ruminating on Logs (Zendcon 2016)
ELK Ruminating on Logs (Zendcon 2016)ELK Ruminating on Logs (Zendcon 2016)
ELK Ruminating on Logs (Zendcon 2016)
 
Tungsten Webinar: v6 & v7 Release Recap, and Beyond
Tungsten Webinar: v6 & v7 Release Recap, and BeyondTungsten Webinar: v6 & v7 Release Recap, and Beyond
Tungsten Webinar: v6 & v7 Release Recap, and Beyond
 
Tuga it 2016 improving your application performance
Tuga it 2016   improving your application performanceTuga it 2016   improving your application performance
Tuga it 2016 improving your application performance
 
19servlets
19servlets19servlets
19servlets
 
Geek Sync | Deployment and Management of Complex Azure Environments
Geek Sync | Deployment and Management of Complex Azure EnvironmentsGeek Sync | Deployment and Management of Complex Azure Environments
Geek Sync | Deployment and Management of Complex Azure Environments
 
Scylla Summit 2016: Compose on Containing the Database
Scylla Summit 2016: Compose on Containing the DatabaseScylla Summit 2016: Compose on Containing the Database
Scylla Summit 2016: Compose on Containing the Database
 

Recently uploaded

Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
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
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991RKavithamani
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
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
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 

Recently uploaded (20)

Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
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
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
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"
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
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
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 

AmI 2015 - Databases in Python

  • 1. Databases in Python MySql, SQLite Accessing persistent storage (Relational databases) from Python code
  • 2. Goal • Making some data ‘persistent’ – When application restarts – When computer restarts • Manage big amounts of data – Not all in-memory • Exploit the power of SQL – Complex data – Complex queries 5/6/2015 Python databases 2
  • 3. Python application General Architecture 5/6/2015 Python databases 3 Flask application Database API definition: PEP 0249 MySQL «connector» module SQLite module MySQL server SQLite library
  • 4. Analyzed databases MySQL • Open source database server • Full featured • Runs as a separate process (may be on a different computer) • Allows concurrent access • http://dev.mysql.com SQLite • Open source file-based storage • Software library integrated in your program (serverless) • Self-contained • https://www.sqlite.org/ 5/6/2015 Python databases 4
  • 5. Other options • MariaDB – fork of MySQL • PostgreSQL – more complex, but more complete than MySQL • Non-relational databases (‘NoSQL’) – won’t be considered here 5/6/2015 Python databases 5
  • 6. PEP 0249 • Python Database API Specification v2.0 – https://www.python.org/dev/peps/pep-0249/ • Specifies a standard API that Python modules that are used to access databases should implement • Does not provide a library nor a module • Third party modules may adhere to these specifications 5/6/2015 Python databases 6
  • 7. Main concepts in PEP 249 • Access to database is provided through a connect method, that returns a Connection object • For executing queries, you need a Cursor object, that can be obtained by the Connection • A cursor may execute() a SQL query, with parameters • A cursor may fetch the results of the query 5/6/2015 Python databases 7
  • 8. Minimal example 5/6/2015 Python databases 8 sql = "SELECT id, original, modified FROM translation" conn = mysql.connector.connect(user='root', password='', host='localhost', database='funnyecho') cursor = conn.cursor() cursor.execute(sql) translations = cursor.fetchall() cursor.close() conn.close() return translations 1 2 3 4 5 6
  • 9. Step 1: defining the query • Write a correct SQL statement, stored as a Python string – sql = "SELECT id, original, modified FROM translation" • Variable arguments may be specified with ‘%s’ placeholders – sql = "INSERT INTO translation (original, modified) VALUES (%s, %s)" 5/6/2015 Python databases 9
  • 10. Step 2: Connecting to the database • Depending on the library, use the provided ‘connect’ method • The method parameters are dependent on the module implementation (non-standard) – conn = mysql.connector.connect(user='root', password='', host='localhost', database='funnyecho') 5/6/2015 Python databases 10
  • 11. Step 5 (a): Clean up • Don’t forget to close the connection, thus freeing up resources on the database server • conn.close() • Write the close statement immediately, otherwise you’ll forget it • Remember not to ‘return’ the function before cleaning up 5/6/2015 Python databases 11
  • 12. Step 3: execute the query • First, obtain a cursor from the connection – cursor = conn.cursor() • Then, execute the query – cursor.execute(sql) • Query parameters (%s placeholders) are specified as a ‘tuple’ argument – cursor.execute(sql, (txtbefore, txtafter) ) – cursor.execute(sql, (txtid,) ) – Beware: one-element tuples require trailing , 5/6/2015 Python databases 12
  • 13. Step 4 (SELECT): Analyze the result • Only if the query was a SELECT • Use various methods of cursor: – cursor.fetchone() # next result – cursor.fetchall() # all remaining results – They return tuples, corresponding to the SELECT’ed columns 5/6/2015 Python databases 13
  • 14. Step 4 (UPDATE): Commit the change • For INSERT, UPDATE and DELETE there is no result • The change is not applied immediately to the database, but needs to be «committed» • conn.commit() – Will commit all pending executed queries in the connection • Must be called before conn.close() • Don’t forget, or you’ll lose your data 5/6/2015 Python databases 14
  • 15. Step 5 (b): Clean up • When the cursor is no longer needed • cursor.close() 5/6/2015 Python databases 15
  • 16. Step 6: Use the results • Analyze the returned data, and do what the application requires for them. • If further queries are needed, go back to step 3 (re-use the same Connection, creating new Cursors) 5/6/2015 Python databases 16
  • 17. Using MySQL • Pre-requisite: a working installation of the mysql server – sudo apt-get install mysql-server – Or download from http://dev.mysql.com/downloads/mysql/ • Download and install the «MySQL Connector for Python» – http://dev.mysql.com/downloads/connector/python/ – Provides the package «mysql.connector» 5/6/2015 Python databases 17
  • 18. MySQL Python Connector • To use: import mysql.connector • Well-done documentation at – http://dev.mysql.com/doc/connector- python/en/index.html 5/6/2015 Python databases 18
  • 19. Connecting with mysql • Basic form – cnx = mysql.connector.connect( • user='joe', • password='xxx', • database='test‘ ) • Additional parameters – http://dev.mysql.com/doc/connector- python/en/connector-python-connectargs.html 5/6/2015 Python databases 19
  • 20. SQLite and Python • SQLite is a simple file-based storage library • Since Python 2.5, it is included by default, in the «sqlite3» package – https://docs.python.org/2/library/sqlite3.html – Developed at https://github.com/ghaering/pysqlite • The «connection» just means specifying the file name 5/6/2015 Python databases 20 import sqlite3 conn = sqlite3.connect('example.db')
  • 21. References and Links • MySQL: http://dev.mysql.com/ • SQLite (C library): https://www.sqlite.org/ • SQLite for Python (installed by default): – Documentation: https://docs.python.org/2/library/sqlite3.html – Developer: https://github.com/ghaering/pysqlite • PEP 249 «Python Database API Specification v2.0»: https://www.python.org/dev/peps/pep-0249/ • MySQL Connector/Python (mysql.connector) – Download & install: http://dev.mysql.com/downloads/connector/python/ – Documentation: http://dev.mysql.com/doc/connector- python/en/index.html 5/6/2015 Python databases 21
  • 22. License • This work is licensed under the Creative Commons “Attribution- NonCommercial-ShareAlike Unported (CC BY-NC-SA 3,0)” License. • You are free: – to Share - to copy, distribute and transmit the work – to Remix - to adapt the work • Under the following conditions: – Attribution - You must attribute the work in the manner specified by the author or licensor (but not in any way that suggests that they endorse you or your use of the work). – Noncommercial - You may not use this work for commercial purposes. – Share Alike - If you alter, transform, or build upon this work, you may distribute the resulting work only under the same or similar license to this one. • To view a copy of this license, visit http://creativecommons.org/license/by-nc-sa/3.0/ 5/6/2015 Python databases 22