Database interfaces
  beheshtraya@gmail.com
Generic Database Interfaces
         and APIs
• ODBC Support
   o pyodbc
   o mxODBC


• ADO Support
   o adodbapi


• JDBC Support
   o Integrated in Jython




Python database interfaces   Fall 2012
pyodbc
• Connect to a Database
     Make a direct connection to a database and
     create a cursor.


   import pyodbc
   cnxn = pyodbc.connect('DRIVER={SQL Server};
                         SERVER=localhost;
                         DATABASE=testdb;
                         UID=user;
                         PWD=pass')
   cursor = cnxn.cursor()



Python database interfaces                       Fall 2012
pyodbc
• Selecting Some Data
      Execute query then fetch results.

cursor.execute("select user_id, user_name from users")
row = cursor.fetchone()
print 'name:', row[1]        # access by column index
print 'name:', row.user_name # or access by name


cursor.execute("select user_id, user_name from users")
rows = cursor.fetchall()
for row in rows:
  print row.user_id, row.user_name


 Python database interfaces                              Fall 2012
pyodbc
• Inserting or deleting
      Execute query then commit changes.


cursor.execute("insert into products(id, name) values ('pyodbc',
'awesome')")
cnxn.commit()



deleted = cursor.execute("delete from products where id <> 'pyodbc'").r
cnxn.commit()




  Python database interfaces                                 Fall 2012
Interfaces for Relational
             Database Systems

• General Purpose Database Systems

• Database Systems for Embedding Into
  Applications




Python database interfaces              Fall 2012
General Purpose Database
                  Systems
•     Microsoft SQL Server
•     Oracle
•     MySQL
•     IBM DB2
•     PostgreSQL
•     Firebird (and Interbase)
•     Informix
•     SAP DB (also known as "MaxDB")
•     …

    Python database interfaces         Fall 2012
• mssql
   o MS SQL Server module for Python




• pymssql
   o A fast MS SQL server client library for Python directly using C API
     instead of ODBC.




Python database interfaces                                         Fall 2012
• cx_Oracle
   o Lite Oracle DB Server module for Python




• DCOracle2
   o    Advanced Python DB API 2.0 adapter for Oracle from
       Zope company.




Python database interfaces                                   Fall 2012
• MySQLdb
   o The most famous library for connecting MySQL
     in python.



• PyMySQL
   o    Pure-Python MySQL client library.




Python database interfaces                          Fall 2012
MySQLdb
• Benefits:
   o    Very fast and optimized ( written in C)
   o    Has big community
   o    Defense SQL injection
   o    very efficient



   import MySQLdb
   conn = mysql.connect(‘localhost’, ‘username’, ‘password’, ‘db name’)
   cursor = conn.cursor()
   cursor.execute(‚Example query‛)
   cursor.commit()    #needed for insert and delete




 Python database interfaces                                        Fall 2012
• Ibm_db
   o Python support for IBM DB2 and IBM Informix



• PyDB2
   o    Pure-Python DB2 interface library.




Python database interfaces                         Fall 2012
• Psycopg
   o The most popular PostgreSQL adapter for the Python




• PyGreSQL
   o Open-source Python module that interfaces to
     a PostgreSQL database




Python database interfaces                                Fall 2012
Interfaces for Non-Relational
            Database Systems

•     MetaKit
•     ZODB
•     Berkeley DB
•     Durus
•     Atop




    Python database interfaces   Fall 2012
Native Python Databases
• Buzhug
   o buzhug is a fast, portable, pure-Python database engine, using a
     pythonic non-SQL syntax for all operations.



• SnakeSQL
   o SnakeSQL is a pure Python SQL database written to remove
     the dependence of the Python Web Modules on 3rd party
     drivers for non-Python databases.




Python database interfaces                                    Fall 2012
Django is a high-level Python Web
    framework that encourages rapid
   development and clean, pragmatic
                  design.



Python database interfaces         Fall 2012
Set database server

DATABASES = {
  'default': {
     'ENGINE': 'django.db.backends.’  # Add 'postgresql_psycopg2', 'mysql', 'sqlite3'
or 'oracle'.
     'NAME': 'main_db.db',            # Or path to database file if using sqlite3.
     'USER': '',
     'PASSWORD': '',
     'HOST': '',           # Set to empty string for localhost.
     'PORT': '',           # Set to empty string for default.
  }
}




 Python database interfaces                                                   Fall 2012
Using multiple database
•     DATABASES = {
        'default': {
              'NAME': 'app_data',
              'ENGINE': 'django.db.backends.postgresql_psycopg2',
              'USER': 'postgres_user',
              'PASSWORD': 's3krit' },
        'users': {
              'NAME': 'user_data',
            'ENGINE': 'django.db.backends.mysql',
            'USER': 'mysql_user',
            'PASSWORD': 'priv4te' }
}




    Python database interfaces                                      Fall 2012
Resources

• Expert Python
  Programming




Python database interfaces               Fall 2012
Resources

• wiki.python.org



• www.djangoproject.com




Python database interfaces               Fall 2012
Python database interfaces   Fall 2012

More Related Content

PPTX
Regular expressions in Python
PDF
Chapter 4 Structured Query Language
PDF
SQL BUILT-IN FUNCTION
PPTX
Database connectivity in python
PPTX
Event In JavaScript
PDF
Python tuple
PDF
Regular expressions in Python
Chapter 4 Structured Query Language
SQL BUILT-IN FUNCTION
Database connectivity in python
Event In JavaScript
Python tuple

What's hot (20)

PPTX
Introduction to java netbeans
PDF
Database design & Normalization (1NF, 2NF, 3NF)
PPTX
array of object pointer in c++
PDF
TypeScript Best Practices
PDF
List , tuples, dictionaries and regular expressions in python
PPT
SQL Tutorial - Basic Commands
PDF
SQL Overview
PPTX
Data structures and algorithms
PDF
Visual basic databases
PPTX
Introduction to React JS for beginners
PPTX
Nodejs Session01
PPTX
Python Lambda Function
PPTX
My Sql Work Bench
PDF
jQuery for beginners
PPT
Databases: Normalisation
PPTX
Procedure and Functions in pl/sql
PPT
Recursion in c
PPT
Oops in Java
PDF
Standard template library
PPTX
Introduction to java netbeans
Database design & Normalization (1NF, 2NF, 3NF)
array of object pointer in c++
TypeScript Best Practices
List , tuples, dictionaries and regular expressions in python
SQL Tutorial - Basic Commands
SQL Overview
Data structures and algorithms
Visual basic databases
Introduction to React JS for beginners
Nodejs Session01
Python Lambda Function
My Sql Work Bench
jQuery for beginners
Databases: Normalisation
Procedure and Functions in pl/sql
Recursion in c
Oops in Java
Standard template library
Ad

Viewers also liked (20)

PPTX
Relational Database Access with Python
PDF
Information is Everything: Marketing in the Age of Disruption
PPTX
Untitled presentation (1)
PPTX
Seventies Swagger
PDF
Educamers - education and gamers
PPT
Fashion of China Andrew Charette
PPT
Understanding social media
PDF
IED - Progettazione 3 - SoyJoy
PPT
Our thought is our life
PDF
Prosumerism
PDF
LEVELAPPME Summer School Report 2012
PDF
IED - Progettazione 4 - AgosDucati, un mondo unico
PPTX
Colors are all around us
PPTX
China presentation
PPTX
Colors are all around us
PPTX
PDF
Camp tech
PPT
Dutch Spices UK
PDF
Qr qrazy
PDF
Искусственный интеллект в краудсорсинге
Relational Database Access with Python
Information is Everything: Marketing in the Age of Disruption
Untitled presentation (1)
Seventies Swagger
Educamers - education and gamers
Fashion of China Andrew Charette
Understanding social media
IED - Progettazione 3 - SoyJoy
Our thought is our life
Prosumerism
LEVELAPPME Summer School Report 2012
IED - Progettazione 4 - AgosDucati, un mondo unico
Colors are all around us
China presentation
Colors are all around us
Camp tech
Dutch Spices UK
Qr qrazy
Искусственный интеллект в краудсорсинге
Ad

Similar to Python database interfaces (20)

PDF
Interface python with sql database.pdf
PDF
Interface python with sql database.pdf--
PDF
Icinga 2009 at OSMC
PDF
Squeak DBX
PDF
Interface python with sql database10.pdf
PDF
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
PPTX
Dev Jumpstart: Build Your First App with MongoDB
PPTX
Relational Database Access with Python ‘sans’ ORM
PPT
PI-RDBMS.ppt
PDF
Www Kitebird Com Articles Pydbapi Html Toc 1
PDF
20171104 hk-py con-mysql-documentstore_v1
PDF
Composable Parallel Processing in Apache Spark and Weld
PDF
The Nitty Gritty of Advanced Analytics Using Apache Spark in Python
PDF
Introduction to Foxx by our community member Iskandar Soesman @ikandars
PDF
Building your first app with MongoDB
PDF
MongoDB World 2016: Get MEAN and Lean with MongoDB and Kubernetes
DOC
Java database programming with jdbc
PPTX
A flexible plugin like data layer - decouple your -_application logic from yo...
PDF
Jump Start on Apache Spark 2.2 with Databricks
PDF
Denodo Partner Connect: Technical Webinar - Ask Me Anything
Interface python with sql database.pdf
Interface python with sql database.pdf--
Icinga 2009 at OSMC
Squeak DBX
Interface python with sql database10.pdf
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
Dev Jumpstart: Build Your First App with MongoDB
Relational Database Access with Python ‘sans’ ORM
PI-RDBMS.ppt
Www Kitebird Com Articles Pydbapi Html Toc 1
20171104 hk-py con-mysql-documentstore_v1
Composable Parallel Processing in Apache Spark and Weld
The Nitty Gritty of Advanced Analytics Using Apache Spark in Python
Introduction to Foxx by our community member Iskandar Soesman @ikandars
Building your first app with MongoDB
MongoDB World 2016: Get MEAN and Lean with MongoDB and Kubernetes
Java database programming with jdbc
A flexible plugin like data layer - decouple your -_application logic from yo...
Jump Start on Apache Spark 2.2 with Databricks
Denodo Partner Connect: Technical Webinar - Ask Me Anything

Recently uploaded (20)

PPTX
Virtual and Augmented Reality in Current Scenario
PDF
MBA _Common_ 2nd year Syllabus _2021-22_.pdf
PDF
Τίμαιος είναι φιλοσοφικός διάλογος του Πλάτωνα
PDF
What if we spent less time fighting change, and more time building what’s rig...
PDF
Trump Administration's workforce development strategy
PPTX
History, Philosophy and sociology of education (1).pptx
PDF
Complications of Minimal Access-Surgery.pdf
PDF
Paper A Mock Exam 9_ Attempt review.pdf.
PDF
CISA (Certified Information Systems Auditor) Domain-Wise Summary.pdf
PPTX
Share_Module_2_Power_conflict_and_negotiation.pptx
PDF
BP 704 T. NOVEL DRUG DELIVERY SYSTEMS (UNIT 1)
PDF
My India Quiz Book_20210205121199924.pdf
PDF
Environmental Education MCQ BD2EE - Share Source.pdf
PPTX
Unit 4 Computer Architecture Multicore Processor.pptx
PPTX
A powerpoint presentation on the Revised K-10 Science Shaping Paper
PDF
David L Page_DCI Research Study Journey_how Methodology can inform one's prac...
PDF
Practical Manual AGRO-233 Principles and Practices of Natural Farming
DOC
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
PDF
Weekly quiz Compilation Jan -July 25.pdf
PDF
HVAC Specification 2024 according to central public works department
Virtual and Augmented Reality in Current Scenario
MBA _Common_ 2nd year Syllabus _2021-22_.pdf
Τίμαιος είναι φιλοσοφικός διάλογος του Πλάτωνα
What if we spent less time fighting change, and more time building what’s rig...
Trump Administration's workforce development strategy
History, Philosophy and sociology of education (1).pptx
Complications of Minimal Access-Surgery.pdf
Paper A Mock Exam 9_ Attempt review.pdf.
CISA (Certified Information Systems Auditor) Domain-Wise Summary.pdf
Share_Module_2_Power_conflict_and_negotiation.pptx
BP 704 T. NOVEL DRUG DELIVERY SYSTEMS (UNIT 1)
My India Quiz Book_20210205121199924.pdf
Environmental Education MCQ BD2EE - Share Source.pdf
Unit 4 Computer Architecture Multicore Processor.pptx
A powerpoint presentation on the Revised K-10 Science Shaping Paper
David L Page_DCI Research Study Journey_how Methodology can inform one's prac...
Practical Manual AGRO-233 Principles and Practices of Natural Farming
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
Weekly quiz Compilation Jan -July 25.pdf
HVAC Specification 2024 according to central public works department

Python database interfaces

  • 2. Generic Database Interfaces and APIs • ODBC Support o pyodbc o mxODBC • ADO Support o adodbapi • JDBC Support o Integrated in Jython Python database interfaces Fall 2012
  • 3. pyodbc • Connect to a Database Make a direct connection to a database and create a cursor. import pyodbc cnxn = pyodbc.connect('DRIVER={SQL Server}; SERVER=localhost; DATABASE=testdb; UID=user; PWD=pass') cursor = cnxn.cursor() Python database interfaces Fall 2012
  • 4. pyodbc • Selecting Some Data Execute query then fetch results. cursor.execute("select user_id, user_name from users") row = cursor.fetchone() print 'name:', row[1] # access by column index print 'name:', row.user_name # or access by name cursor.execute("select user_id, user_name from users") rows = cursor.fetchall() for row in rows: print row.user_id, row.user_name Python database interfaces Fall 2012
  • 5. pyodbc • Inserting or deleting Execute query then commit changes. cursor.execute("insert into products(id, name) values ('pyodbc', 'awesome')") cnxn.commit() deleted = cursor.execute("delete from products where id <> 'pyodbc'").r cnxn.commit() Python database interfaces Fall 2012
  • 6. Interfaces for Relational Database Systems • General Purpose Database Systems • Database Systems for Embedding Into Applications Python database interfaces Fall 2012
  • 7. General Purpose Database Systems • Microsoft SQL Server • Oracle • MySQL • IBM DB2 • PostgreSQL • Firebird (and Interbase) • Informix • SAP DB (also known as "MaxDB") • … Python database interfaces Fall 2012
  • 8. • mssql o MS SQL Server module for Python • pymssql o A fast MS SQL server client library for Python directly using C API instead of ODBC. Python database interfaces Fall 2012
  • 9. • cx_Oracle o Lite Oracle DB Server module for Python • DCOracle2 o Advanced Python DB API 2.0 adapter for Oracle from Zope company. Python database interfaces Fall 2012
  • 10. • MySQLdb o The most famous library for connecting MySQL in python. • PyMySQL o Pure-Python MySQL client library. Python database interfaces Fall 2012
  • 11. MySQLdb • Benefits: o Very fast and optimized ( written in C) o Has big community o Defense SQL injection o very efficient import MySQLdb conn = mysql.connect(‘localhost’, ‘username’, ‘password’, ‘db name’) cursor = conn.cursor() cursor.execute(‚Example query‛) cursor.commit() #needed for insert and delete Python database interfaces Fall 2012
  • 12. • Ibm_db o Python support for IBM DB2 and IBM Informix • PyDB2 o Pure-Python DB2 interface library. Python database interfaces Fall 2012
  • 13. • Psycopg o The most popular PostgreSQL adapter for the Python • PyGreSQL o Open-source Python module that interfaces to a PostgreSQL database Python database interfaces Fall 2012
  • 14. Interfaces for Non-Relational Database Systems • MetaKit • ZODB • Berkeley DB • Durus • Atop Python database interfaces Fall 2012
  • 15. Native Python Databases • Buzhug o buzhug is a fast, portable, pure-Python database engine, using a pythonic non-SQL syntax for all operations. • SnakeSQL o SnakeSQL is a pure Python SQL database written to remove the dependence of the Python Web Modules on 3rd party drivers for non-Python databases. Python database interfaces Fall 2012
  • 16. Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. Python database interfaces Fall 2012
  • 17. Set database server DATABASES = { 'default': { 'ENGINE': 'django.db.backends.’ # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'main_db.db', # Or path to database file if using sqlite3. 'USER': '', 'PASSWORD': '', 'HOST': '', # Set to empty string for localhost. 'PORT': '', # Set to empty string for default. } } Python database interfaces Fall 2012
  • 18. Using multiple database • DATABASES = { 'default': { 'NAME': 'app_data', 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'USER': 'postgres_user', 'PASSWORD': 's3krit' }, 'users': { 'NAME': 'user_data', 'ENGINE': 'django.db.backends.mysql', 'USER': 'mysql_user', 'PASSWORD': 'priv4te' } } Python database interfaces Fall 2012
  • 19. Resources • Expert Python Programming Python database interfaces Fall 2012