20160229_modernapplicationdevelopment_python_kpatenge

27
Copyright © 2014 Oracle and/or its affiliates. All rights reserved. | Python und die Oracle Datenbank Einfacher als man denkt. Karin Patenge | Leitende Systemberaterin | [email protected] Oracle Deutschland B.V. & Co KG Twitter: @ModernAppDev12c | Web: http://tinyurl.com/ModernAppDev12c

Upload: karin-patenge

Post on 17-Feb-2017

130 views

Category:

Technology


0 download

TRANSCRIPT

Page 1: 20160229_ModernApplicationDevelopment_Python_KPatenge

Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

Python und die Oracle Datenbank – Einfacher als man denkt.

Karin Patenge | Leitende Systemberaterin | [email protected] Oracle Deutschland B.V. & Co KG Twitter: @ModernAppDev12c | Web: http://tinyurl.com/ModernAppDev12c

Page 2: 20160229_ModernApplicationDevelopment_Python_KPatenge

Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

Agenda

1

2

3

4

Einordnung

Was ist Python? Für wen ist Python?

Mit Python auf der Oracle Datenbank arbeiten

Zusammenfassung

Weiterführende Informationen

3

5

Page 3: 20160229_ModernApplicationDevelopment_Python_KPatenge

Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

1

2

3

4

Einordnung

Was ist Python? Für wen ist Python?

Mit Python auf der Oracle Datenbank arbeiten

Zusammenfassung

Weiterführende Informationen

4

5

Page 4: 20160229_ModernApplicationDevelopment_Python_KPatenge

Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

Oracle Datenbank 12c für EntwicklerInnen

PROGRAMMIER-SPRACHE

TREIBER

C OCI

C++ OCCI

Java JDBC

.NET ODP.NET

Node.js node-oracledb

Python cx_Oracle

PHP OCI8, PDO_OCI

R ROracle

Perl DBD::Oracle

Ruby ruby-oci8

6

Die Datenbank für alle wichtigen Plattformen

… und ODBC, OLE DB, Pro*C, Pro*COBOL, Pro*Fortran, SQLJ

Third-party Drivers

Open Source Drivers

(Oracle contributions)

Proprietary Drivers

Page 5: 20160229_ModernApplicationDevelopment_Python_KPatenge

Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

Node.js: node-oracledb 1.4 im November 2015 released • “Add-on” für Node.js – Erstes Release von Oracle im Januar 2015 • Wachsende Community – Monatliche Updates – Wachsende Downloadzahlen • https://github.com/oracle/node-oracledb

Python: cx_Oracle 5.2 im Juni 2015 released • Ergänzungen um Oracle DB 12c Features • http://cx-oracle.sourceforge.net

PHP: OCI8 2.1.0 im Dezember 2015 released • Größeres Refactoring von Oracle für PHP 7 Release • http://pecl.php.net/package/oci8

R: ROracle 1.2-1 im Juli 2015 released • Signifikante Performance-Verbesserungen • http://cran.r-project.org/web/packages/ROracle

Treiber von Oracle für wichtige Plattformen

7

Page 6: 20160229_ModernApplicationDevelopment_Python_KPatenge

Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

1

2

3

4

Einordnung

Was ist Python? Für wen ist Python?

Mit Python auf der Oracle Datenbank arbeiten

Zusammenfassung

Weiterführende Informationen

9

5

Page 7: 20160229_ModernApplicationDevelopment_Python_KPatenge

Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

Die Programmiersprache Python

• Universelle, höhere Programmiersprache • Unterstützung unterschiedlicher

Programmierparadigmen – objektorientiert, aspektorientiert, funktional

• Dynamische Typisierung – Deklarationszwang für Variablen entfällt

• Häufigste Nutzung als Skriptsprache • Programmstruktur wird durch Einrückungen

abgebildet

• Versionslinien: Python 2.x / Python 3.x – 3.x mit substantiellen Verbesserungen

• Basis: Read-Evaluate-Print Loop (REPL)

• Empfohlene Dateiendung für Skripte: .py

• Warum Python? – Kompakter Kern

– Leicht zu erlernen

– Leicht lesbar - klare, übersichtliche Syntax - Wenige Schlüsselworte

– Leicht anzuwenden

– Eingebaute umfangreiche Standard-bibliothek und zahlreiche Pakete

• Sonstiges – Erscheinungsjahr 1991

– Python Software Foundation Lizenz

– www.python.org

– Prompt: „>>>“

– >>> help() | >>> exit()

10

Page 8: 20160229_ModernApplicationDevelopment_Python_KPatenge

Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

Ein wenig Python Code „zum Aufwärmen“ [oracle@bigdatalite ~]$ python Python 2.6.6 (r266:84292, Jul 23 2015, 05:13:40) [GCC 4.4.7 20120313 (Red Hat 4.4.7-16)] on linux2 Type "help", "copyright", "credits" or "license"

for more information. >>> # Einfache arithmetische Berechnung ... 27*3 81 >>> # Arbeit mit Variablen ... var=123 >>> print var 123 >>> # Math-Paket importieren. Konstanten und

Funktionen. ... import math >>> math.pi 3.1415926535897931 >>> print math.sin(math.pi/6) 0.49999999999999994 >>> ...

11

>>> from random import random, randint >>> geraten=False >>> Zahl=randint(1,20) >>> while not geraten: ... try: ... MeineZahl=int(input("Rate eine Zahl

zwischen 1 und 20.\n")) ... except ValueError: ... print("Das ist keine gueltige Zahl.") ... continue ... if MeineZahl > Zahl: ... print("Zu gross") ... elif MeineZahl < Zahl: ... print("Zu klein") ... else: ... geraten=True ... print("Herzlichen Glueckwunsch") ... Rate eine Zahl zwischen 1 und 20. ... ...

Page 9: 20160229_ModernApplicationDevelopment_Python_KPatenge

Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

1

2

3

4

Einordnung

Was ist Python? Für wen ist Python?

Mit Python auf der Oracle Datenbank arbeiten

Zusammenfassung

Weiterführende Informationen

12

5

Page 10: 20160229_ModernApplicationDevelopment_Python_KPatenge

Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

Python in der Praxis

• Schritt 1: Die Demo-Umgebung

• Schritt 2: Vorhandensein von Python prüfen und ggf. installieren

• Schritt 3: Eine Python-Variante von „Hello World“

• Schritt 4: Das Python Paket cx_Oracle

• Schritt 5: Mit Python in die Oracle DB gehen

• Schritt 6: Abfragen auf Tabellen in der Oracle DB

• Schritt 7: Arbeiten mit JSON-Dokumenten in der Oracle DB

• Schritt 8: SDO_GEOMETRY-Daten aus der Oracle DB auf die Karte bringen

• ... 13

Page 11: 20160229_ModernApplicationDevelopment_Python_KPatenge

Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

Python in der Praxis Schritt 1: Die Demo-Umgebung

• Prebuilt Database Application Developer VM herunterladen http://www.oracle.com/technetwork/community/developer-vm/index.html und in Virtual Box als Appliance Importieren

• Initialen Sicherungspunkt setzen • VM starten (oracle/oracle) • VM einrichten

– Applications > System Tools > Settings > Region & Language

• VB Guest Additions ggf. installieren – Geräte > Medium mit Gasterweiterungen einlegen ... > Run ...

– Geräte > Drag‘n‘ Drop > Bidirektional sowie Geräte > Shared Clipboard > Bidirektional

14

Page 12: 20160229_ModernApplicationDevelopment_Python_KPatenge

Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

Python in der Praxis Schritt 2: Vorhandensein von Python prüfen und ggf. installieren (1)

• Python ist vorinstalliert in den meisten Linux Distributionen

15

[oracle@localhost Desktop]$ python Python 2.7.5 (default, May 8 2014, 17:35:19) [GCC 4.8.2 20140120 (Red Hat 4.8.2-16)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> [oracle@localhost Desktop]$ python -v # installing zipimport hook import zipimport # builtin # installed zipimport hook # /usr/lib64/python2.7/site.pyc matches /usr/lib64/python2.7/site.py

Page 13: 20160229_ModernApplicationDevelopment_Python_KPatenge

Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

Python in der Praxis Schritt 2: Vorhandensein von Python prüfen und ggf. installieren (2)

• Zusätzliche Software-Komponenten: – PyPI (Pakete finden) , pip (Pakete laden) , Python Tools (u.a. IDLE IDE), Django (Web-Framework)

– Ggf. Oracle Database Client Software

16

[oracle@localhost Downloads]$ sudo -i [root@localhost ~]# python get-pip.py --proxy http://... [root@localhost Downloads]# python get-pip.py --proxy http://... Collecting pip /tmp/tmpercQK8/pip.zip/pip/_vendor/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning. Downloading pip-7.1.2-py2.py3-none-any.whl (1.1MB) 100% |████████████████████████████████| 1.1MB 295kB/s Collecting wheel Downloading wheel-0.26.0-py2.py3-none-any.whl (63kB) 100% |████████████████████████████████| 65kB 3.8MB/s Installing collected packages: pip, wheel Successfully installed pip-7.1.2 wheel-0.26.0

Page 14: 20160229_ModernApplicationDevelopment_Python_KPatenge

Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

Python in der Praxis Schritt 3: Python-Varianten von „Hello World“

17

[oracle@bigdatalite ~]$ python Python 2.6.6 (r266:84292, Jul 23 2015, 05:13:40) [GCC 4.4.7 20120313 (Red Hat 4.4.7-16)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> var = "hello world" >>> print(var) hello world >>> >>> var = "Hallo " >>> user_name = raw_input("Wie heisst Du? ") Wie heisst Du? Karin >>> output = var + user_name.upper() >>> print(output) Hallo KARIN >>> output.split() ['Hallo', 'KARIN']

Page 15: 20160229_ModernApplicationDevelopment_Python_KPatenge

Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

Python in der Praxis Schritt 4: Das Python Paket cx_Oracle

18

• Zugriff auf die Oracle Datenbank über Python´s Database API

• Download http://cx-oracle.sourceforge.net

• Unterstützt : Datenbank Versionen 11.2 und 12.1 für Python 2.x als auch 3.x

• Dokumenation https://cx-oracle.readthedocs.org/en/latest/

• ORACLE_HOME Umgebungsvariable setzen

• Installation und Überprüfung: > sudo pip install cx_Oracle –-proxy http://...

> python

>>> help('modules')

• Dokumentation für Python: > python –m pydoc cx_Oracle

Page 16: 20160229_ModernApplicationDevelopment_Python_KPatenge

Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

Python in der Praxis Schritte 5+6: Beispiel-Code Arbeiten mit einer Oracle DB Verbindung

[oracle@bigdatalite ~]$ python Python 2.6.6 (r266:84292, Jul 23 2015, 05:13:40) [GCC 4.4.7 20120313 (Red Hat 4.4.7-16)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import cx_Oracle >>> con = cx_Oracle.connect('scott/tiger@localhost/orcl') >>> print(con.version) 12.1.0.2.0 >>> cur=con.cursor() >>> cur.execute('select * from emp order by ename') <cx_Oracle.Cursor on <cx_Oracle.Connection to scott@localhost/orcl>> >>> for row in cur: ... print(row) (7876, 'ADAMS', 'CLERK', 7788, datetime.datetime(1987, 5, 23, 0, 0), 1100.0, None, 20) >>> cur.close() >>> con.close()

19

Page 17: 20160229_ModernApplicationDevelopment_Python_KPatenge

Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

Python in der Praxis Schritt 7: Beispiel-Code Arbeit mit JSON Dokumenten in der Oracle DB

>>> import cx_Oracle >>> con=cx_Oracle.connect('scott/tiger@localhost/orcl') >>> cur=con.cursor() >>> cur.execute('create table test_json (id number generated always as identity, json_data clob)')

>>> cur.execute('insert into test_json(json_data) values\ ... (\'{rating: "3.0 out of 5 stars",title: "Quality product",\ ... customer_name: "GeirGjorven",date: "on 29 September 2014",\ ... colour: "Colour Name: Envoycolour",purchase_type: "Verified Purchase",\ ... comment: "Good service"}\')') >>> cur.execute('commit') >>> cur.execute('select id from test_json where json_data IS JSON') <cx_Oracle.Cursor on <cx_Oracle.Connection to scott@localhost/orcl>> >>> >>> for row in cur: ... print(row) ... ...

20

Page 18: 20160229_ModernApplicationDevelopment_Python_KPatenge

Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

Python in der Praxis Schritt 8: Raumbezogene Daten auf Karten darstellen

21

• Raumbezogene Daten als SDO_GEOMETRY in der Oracle DB gespeichert (Schema: WORLD_SAMPLE)

• Installieren der zugehörigen Packages • MATPLOTLIB > sudo pip install matplotlib –-proxy http://...

• NUMPY > sudo pip install numpy –-proxy http://...

• und BASEMAP

– Download über http://sourceforge.net/projects/matplotlib/files/matplotlib-toolkits/

• Basemap-Dokumentation bzw. Tutorial

• http://matplotlib.org/basemap/index.html

• http://basemaptutorial.readthedocs.org/en/latest/index.html

Page 19: 20160229_ModernApplicationDevelopment_Python_KPatenge

Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

Python in der Praxis Schritt 8: Beispiel-Code Raumbezogene Daten auf einer Karte darstellen (a)

>>> from mpl_toolkits.basemap import Basemap >>> import matplotlib.pyplot as plt >>> map = Basemap(projection='merc', lat_0 = 52, lon_0 = 12,resolution = 'i', area_thresh = 1, llcrnrlon=-30, llcrnrlat=30, urcrnrlon=120, urcrnrlat=75)

>>> map.drawcoastlines() <matplotlib.collections.LineCollection object at 0x3799450> >>> map.drawcountries() <matplotlib.collections.LineCollection object at 0x3583650> >>> map.fillcontinents(color = 'coral', lake_color='aqua') [<matplotlib.patches.Polygon object at 0x5069050>, <matplotlib.patches.Polygon ... >>> map.drawmapboundary(fill_color='aqua') <matplotlib.patches.Rectangle object at 0x3884d90> >>> plt.show()

22

Page 20: 20160229_ModernApplicationDevelopment_Python_KPatenge

Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

Python in der Praxis Schritt 8: Beispiel-Code Raumbezogene Daten in Oracle DB abfragen (b)

>>> cur.execute('select official_name from wom_poi_city_center p where sdo_nn(p.geometry, sdo_geometry(2001,8307, sdo_point_type(10.0, 50.0, null), null, null), \'sdo_num_res=5\') = \'TRUE\'')

<cx_Oracle.Cursor on <cx_Oracle.Connection to world_sample@localhost/orcl>> >>> for row in cur: print(row) ... ... ('DORTMUND',) ... ... >>> res = cur.execute('select * from table(sdo_pointinpolygon(cursor(select p.geometry.sdo_point.x lon, p.geometry.sdo_point.y lat, poi_id id, name from wom_poi p), sdo_geometry (2003,8307,null,mdsys.sdo_elem_info_array(1, 1003, 3),mdsys.sdo_ordinate_array(6.0, 47.0, 15.0, 55.0)),0.05))')

>>> for row in res: print(row) ... (7.6277399999999993, 48.544930000000001, 170, 'AEROPORT STRASBOURG INTERNATIONAL') ... ...

23

Page 21: 20160229_ModernApplicationDevelopment_Python_KPatenge

Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

Python in der Praxis Schritt 8: Beispiel-Code Raumbezogene Daten aus Oracle DB auf Karten zeigen (a+b)

>>> cur.execute('select * from table( sdo_pointinpolygon(cursor(select p.geometry.sdo_point.x lon, p.geometry.sdo_point.y lat, from wom_poi p), sdo_geometry (2003,8307,null,mdsys.sdo_elem_info_array(1, 1003, 3),mdsys.sdo_ordinate_array(6.0, 47.0, 15.0, 55.0)),0.05))')

<cx_Oracle.Cursor on <cx_Oracle.Connection to world_sample@localhost/orcl>> >>> row = cur.fetchone() >>> lons = [] >>> lats = [] >>> while row: ... lons.append(row[0]) ... lats.append(row[1]) ... row = cur.fetchone() >>> map = Basemap(projection='merc', lat_0 = 50, lon_0 = 10, resolution = 'i', area_thresh = 0.1,

llcrnrlon=6, llcrnrlat=47, urcrnrlon=15, urcrnrlat=55) ... ... >>> x,y = map(lons,lats) >>> map.plot(x,y,'ro',markersize=10) [<matplotlib.lines.Line2D object at 0x40fc890>] >>> plt.show()

24

Page 22: 20160229_ModernApplicationDevelopment_Python_KPatenge

Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

1

2

3

4

Einordnung

Was ist Python? Für wen ist Python?

Mit Python auf der Oracle Datenbank arbeiten

Zusammenfassung

Weiterführende Informationen

25

5

Page 23: 20160229_ModernApplicationDevelopment_Python_KPatenge

Copyright © 2014 Oracle and/or its affiliates. All rights reserved. | 26

Zusammenfassung

• Python – Eine Option mehr für die Anwendungsentwicklung – Für einen immer größeren Kreis von Personen, die Anwendungen entwickeln

• Einfacher Zugriff auf die Oracle DB mittels cx_Oracle Treiber – 12c Features inklusive

– Alle Datenbank-Editionen

– DML, DDL, SELECT und mehr

• Flexibel kombinierbar mit Standardbibliothek und vielen weiteren frei verfügbaren Paketen – Beliebig erweiterbar mit neuen Paketen

• Python ist leicht zu erlernen

Page 24: 20160229_ModernApplicationDevelopment_Python_KPatenge

Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

1

2

3

4

Einordnung

Was ist Python? Für wen ist Python?

Mit Python auf der Oracle Datenbank arbeiten

Zusammenfassung

Weiterführende Informationen

27

5

Page 25: 20160229_ModernApplicationDevelopment_Python_KPatenge

Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

Weiterführende Informationen (I)

• Mastering Oracle+Python Series

– http://www.oracle.com/technetwork/articles/dsl/mastering-oracle-python-1391323.html

• Tutorial: Using Python with Oracle Database 11g

– http://www.oracle.com/technetwork/articles/dsl/python-091105.html

• Python Discussion Forum

– https://community.oracle.com/community/database/developer-tools/python

• Twitter – @ghrd (Christopher Jones, Oracle Product Manager , u.a. Scripting Languages)

• Blog

– https://blogs.oracle.com/opal/ (Christopher Jones´ Blog)

28

Page 26: 20160229_ModernApplicationDevelopment_Python_KPatenge

Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

Weiterführende Informationen (II)

• Python Relational Database API

– https://wiki.python.org/moin/DatabaseProgramming

• cx_Oracle Dokumentation

– https://cx-oracle.readthedocs.org/en/latest/

• cx_Oracle Source Code

– https://bitbucket.org/anthony_tuininga/cx_oracle/

29

Page 27: 20160229_ModernApplicationDevelopment_Python_KPatenge

Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

[email protected] Blog: http://oracle-spatial.blogspot.de Twitter: @kpatenge