SlideShare a Scribd company logo
Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
Creating Python application with
MySQL High Availability Database
Service
Ivan Ma
ivan-cs.ma@oracle.com
2016-10-29
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
Safe Harbor Statement
The following is intended to outline our general product direction. It is intended for
information purposes only, and may not be incorporated into any contract. It is not a
commitment to deliver any material, code, or functionality, and should not be relied upon
in making purchasing decisions. The development, release, and timing of any features or
functionality described for Oracle’s products remains at the sole discretion of Oracle.
2
Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
Program Agenda
3
MySQL High Availability Intro
Python – Connecting to Database
Making Query to Database
Python – Failover (HA) connection to Database
Flask – Web App Sample
1
2
3
4
5
Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
Overview
• MySQL as Database
– Highly Available Configuration and Setup
• Python
– The Programming Language
– Using Framework (e.g. FLASK )
– Database Connection
– Query
– Row Result Processing
– Error Handling
Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
Today
• Introducing
– MySQLGroup Replication
– MySQLReplication
– MySQLRouter
– MySQLInnoDB Cluster
• MySQL Connector/Python
– Connecting to MySQL
– SELECT statements
– Looping Result
– Executing Stored Procedure
– ErrorHandling in Python with MySQL
– multi-host connection with MySQL
Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
A Quick Walk thru of MySQL HA
• MySQL High Availability
– Redundancy is the Key
• MySQL Replication
• MySQL Semi-SyncReplication
• MySQL Group Replication
• Shared Storage with OS Clustering
• MySQL Cluster
• Application Connection to MySQL
– Connector / Driver
• Connector/ Python
• Connector / Java
• Connector / .NET, PHP, etc…
Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
A Quick Walk thru of MySQL HA
• MySQL High Availability
– Redundancy is the Key
• MySQL Replication
• MySQL Semi-SyncReplication
• MySQL Group Replication (RC)
• Shared Storage with OS Clustering – MySQL service
• MySQL Cluster
• Application Connection to MySQL
– Connector / Driver
• Connector/ Python
• Connector / Java
• Connector / .NET, PHP, etc…
MySQL Router
Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
MySQL
Group Replication (Release Candidate)
Natively distributed and highly available replica sets
Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
MySQL Group Replication: What Does It Provide?
• A highly available distributed MySQL database service
– Removes the need for manually handling server fail-over
– Provides distributed fault tolerance
– Enables Active/Active update anywhere setups
– Automates reconfiguration (adding/removing nodes, crashes, failures)
– Automatically detects and handles conflicts
9
Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
MySQL Server: Core
• Server calls into the plugin through a generic
interface
– Most server internals are hidden from the plugin
• Plugin interacts with the server through a generic
interface
– Replication plugin determines the fate of the commit
operation through a well defined server interface
– The plugin makes use of the relay log infrastructure to
inject changes in the receiving server
10
GCS API
Replication
Plugin
Plugin API
MySQL
Server
Group Com. Engine
GCS API
Replication
Plugin
Plugin API
MySQL
Server
Group Com. Engine
Network
Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
MyQL Connector / Python
Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
MySQL Connector / Python
• To download the Connetor/Python,
– https://dev.mysql.com/downloads/connector/python/
Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
Connecting MySQL
• import mysql.connector
• import sys
• _pass = ''
• if len(sys.argv) > 1 :
• _pass = sys.argv[1]
• cnx = mysql.connector.connect(user='root', password=_pass,
host='127.0.0.1',port=3306, database='mysql')
• cnx.close()
Copyright © 2016, Oracle and/or its affiliates. All rights reserved. | 14
Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
“connection” – MySQLConnection Class
• frommysql.connector import (connection)
• import sys
• _pass='';
• if len(sys.argv) > 1 :
• _pass=sys.argv[1]
• cnx = connection.MySQLConnection(user='root', password=_pass,
host='127.0.0.1',port=3306, database='mysql')
• cnx.close()
Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
Connection Pooling
16
Implicit
Explicit
Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
Connecting MySQL using Dictionary config
• import mysql.connector
• import sys
• _pass='';
• if len(sys.argv) > 1 :
• _pass=sys.argv[1]
• config = { 'user': 'root', 'password': '', 'host': '127.0.0.1', 'database': 'mysql',
• 'raise_on_warnings': True, }
• cnx = mysql.connector.connect(**config)
• cnx.close()
Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
Error Handling in Connection (try …. except…finally)
• try:
• cnx = mysql.connector.connect(user='root', host='127.0.0.1', port=3306,
• password=_pass,
• database=_db)
• print("connect success")
• except mysql.connector.Error as err:
• if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
• print("Something is wrong with your user name or password")
• elif err.errno == errorcode.ER_BAD_DB_ERROR:
• print("Database does not exist")
• else:
• print(err)
• finally:
• print ("Finally - close connection")
• cnx.close()
Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
SELECT
• cnx = mysql.connector.connect(**config)
• operation = “select ……. from …..; select …. from ….”
• cursor = cnx.cursor()
• try:
• ……
• except mysql.connector.Error as err:
• print(err.msg)
• cursor.close()
• cnx.close()
19
for result in cursor.execute(operation, multi=True):
if result.with_rows:
print("rows producted by statement '{}':".format(result.statement))
row = cursor.fetchone()
while row:
print(row)
row = cursor.fetchone()
else:
print("Number of rows affeted by statement '{}':{}".format(result.statement,
result.rowcount))
Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
Failover Connection Property
• operation ='SELECT @@hostname, @@port, employees.*from employees limit 10‘
• try:
• for result in cursor.execute(operation, multi=True):
• if result.with_rows:
• print("rows producted by statement '{}':".format(result.statement))
• row = cursor.fetchone()
• whilerow:
• print(row)
• row = cursor.fetchone()
• else:
• print("Number of rows affeted by statement '{}':{}".format(result.statement, result.rowcount))
• except mysql.connector.Error as err:
• print(err.msg)
• cursor.close()
• cnx.close()
20
config = {
'raise_on_warnings': True,
'failover' : [
{ 'user': 'root‘, 'password': '‘, 'host': '127.0.0.1‘, 'port': 3306,
'database': 'employees', },
{ 'user': 'root‘, 'password': '‘, 'host': '127.0.0.1‘, 'port': 3306,
'database': 'employees',}
]
}
cnx = mysql.connector.connect(**config)
Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
Program Agenda
21
MySQL High Availability Intro
Python – Connecting to Database
Making Query to Database
Python – Failover (HA) connection to Database
Flask – Web App Sample
1
2
3
4
5
Copyright © 2016, Oracle and/or its affiliates. All rights reserved. | 22
Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
Home Page with Flask
• from flask import Flask, render_template, request, json
• importmysql.connector
• from mysql.connector import errorcode
• app = Flask(__name__)
• @app.route("/")
• @app.route("/main")
• defmain():
• return render_template('03-index.html')
23
config = {
'user': 'root',
'password': '',
'host': '127.0.0.1',
'port': 3316,
'database': 'pycon2016hk',
'raise_on_warnings': True,
}
Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
Register – Calling Stored Procedure
• @app.route("/Register", methods=["POST","GET"])
• def register():
• try:
• _name = request.form['inputName']
• _password = request.form['inputPassword']
• # validate the values
• if _name and _password:
•
• else:
• return '<p>Please Enter the required fields!!</p>'
• except Exception as e:
• return '<p><span>DB Error' + str(e) +'</spand></p>'
• finally:
******************************************
24
conn = mysql.connector.connect(**config)
cursor = conn.cursor()
cursor.callproc("sp_user",[ _name, _password])
if len(list(cursor.stored_results())) is 0:
conn.commit()
return 'Message:User created successfully!‘
else:
data = []
for result in cursor.stored_results():
data.append(str(result.fetchall()))
return '<p><span>Error:' + str(data) + '</span></p>'
Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
THANK YOU!
25
20161029 py con-mysq-lv3

More Related Content

PDF
MySQL JSON Functions
PDF
My sql 5.7-upcoming-changes-v2
PDF
MySQL 5.7 + JSON
PDF
MySQL Group Replication - an Overview
PDF
What's New MySQL 8.0?
PPTX
Fosdem17 honeypot your database server
PDF
MySQL 8.0.18 - New Features Summary
PDF
MySQL Manchester TT - Performance Tuning
MySQL JSON Functions
My sql 5.7-upcoming-changes-v2
MySQL 5.7 + JSON
MySQL Group Replication - an Overview
What's New MySQL 8.0?
Fosdem17 honeypot your database server
MySQL 8.0.18 - New Features Summary
MySQL Manchester TT - Performance Tuning

What's hot (20)

PDF
Solving Performance Problems Using MySQL Enterprise Monitor
PDF
Mysql nowwhat
PDF
MySQL 8.0.17 - New Features Summary
PPTX
BGOUG 2014 Decrease Your MySQL Attack Surface
PDF
Which cloud provider for your oracle database
PDF
MySQL 8.0.16 New Features Summary
PDF
MySQL High Availability with Group Replication
PDF
MySQL Monitoring 101
PDF
MySQL 8.0.22 - New Features Summary
ODP
The Query Rewrite Plugin Interface: Writing Your Own Plugin
PDF
MySQL For Linux Sysadmins
PDF
MySQL sys schema deep dive
ODP
MySQL 5.7 - What's new and How to upgrade
PDF
MySQL High Availability Solutions - Avoid loss of service by reducing the r...
PDF
MySQL Performance Best Practices
PDF
MySQL's Performance Schema, SYS Schema and Workbench Integration
PDF
Exploring mysql cluster 7.4
PDF
My sql crashcourse_2012
PDF
MySQL: From Single Instance to Big Data
PDF
MySQL Day Paris 2018 - What’s New in MySQL 8.0 ?
Solving Performance Problems Using MySQL Enterprise Monitor
Mysql nowwhat
MySQL 8.0.17 - New Features Summary
BGOUG 2014 Decrease Your MySQL Attack Surface
Which cloud provider for your oracle database
MySQL 8.0.16 New Features Summary
MySQL High Availability with Group Replication
MySQL Monitoring 101
MySQL 8.0.22 - New Features Summary
The Query Rewrite Plugin Interface: Writing Your Own Plugin
MySQL For Linux Sysadmins
MySQL sys schema deep dive
MySQL 5.7 - What's new and How to upgrade
MySQL High Availability Solutions - Avoid loss of service by reducing the r...
MySQL Performance Best Practices
MySQL's Performance Schema, SYS Schema and Workbench Integration
Exploring mysql cluster 7.4
My sql crashcourse_2012
MySQL: From Single Instance to Big Data
MySQL Day Paris 2018 - What’s New in MySQL 8.0 ?
Ad

Viewers also liked (15)

PPTX
Hardware y software
PPTX
Datos personales
PDF
Hkosc group replication-lecture_lab07
PPT
Telecom lect 5
PPTX
Yaninis
PPTX
Telecollaborative Exchange and Intercultural Education
PPTX
lección 02- creación de Virtual Host laravel 5 + Xampp + Windows
PDF
Efficient Context-sensitive Output Escaping for Javascript Template Engines
PPT
Telecom lect 6
PDF
How to insert json data into my sql using php
PDF
Operational Buddhism: Building Reliable Services From Unreliable Components -...
PDF
Advanced Percona XtraDB Cluster in a nutshell... la suite
PDF
PetroSync - Seismic Interpretation
PPTX
Tuinen in kunst, tuinen als kunst - Renaissance Italië en Frankrijk
PPSX
Palestinaentiemposdejesus
Hardware y software
Datos personales
Hkosc group replication-lecture_lab07
Telecom lect 5
Yaninis
Telecollaborative Exchange and Intercultural Education
lección 02- creación de Virtual Host laravel 5 + Xampp + Windows
Efficient Context-sensitive Output Escaping for Javascript Template Engines
Telecom lect 6
How to insert json data into my sql using php
Operational Buddhism: Building Reliable Services From Unreliable Components -...
Advanced Percona XtraDB Cluster in a nutshell... la suite
PetroSync - Seismic Interpretation
Tuinen in kunst, tuinen als kunst - Renaissance Italië en Frankrijk
Palestinaentiemposdejesus
Ad

Similar to 20161029 py con-mysq-lv3 (20)

PDF
20160821 coscup-my sql57docstorelab01
PDF
MySQL Document Store
PDF
RMOUG MySQL 5.7 New Features
PDF
What's new in MySQL 5.7, Oracle Virtual Technology Summit, 2016
PDF
MySQL High Availability -- InnoDB Clusters
PDF
MySQL InnoDB Cluster and NDB Cluster
PPTX
MySQL Quick Dive
PDF
Reactive Java Programming: A new Asynchronous Database Access API by Kuassi M...
PDF
MySQL Fabric
PDF
Develop Python Applications with MySQL Connector/Python
PDF
20151010 my sq-landjavav2a
PDF
Basic MySQL Troubleshooting for Oracle DBAs
PDF
20190615 hkos-mysql-troubleshootingandperformancev2
PPTX
MySQL London Tech Tour March 2015 - MySQL Fabric
PDF
MySQL Shell - The Best MySQL DBA Tool
PDF
MySQL & Oracle Linux Keynote at Open Source India 2014
PPTX
My sql8 innodb_cluster
PDF
20200613 my sql-ha-deployment
PPTX
OUGLS 2016: Guided Tour On The MySQL Source Code
PDF
MySQL for Software-as-a-Service (SaaS)
20160821 coscup-my sql57docstorelab01
MySQL Document Store
RMOUG MySQL 5.7 New Features
What's new in MySQL 5.7, Oracle Virtual Technology Summit, 2016
MySQL High Availability -- InnoDB Clusters
MySQL InnoDB Cluster and NDB Cluster
MySQL Quick Dive
Reactive Java Programming: A new Asynchronous Database Access API by Kuassi M...
MySQL Fabric
Develop Python Applications with MySQL Connector/Python
20151010 my sq-landjavav2a
Basic MySQL Troubleshooting for Oracle DBAs
20190615 hkos-mysql-troubleshootingandperformancev2
MySQL London Tech Tour March 2015 - MySQL Fabric
MySQL Shell - The Best MySQL DBA Tool
MySQL & Oracle Linux Keynote at Open Source India 2014
My sql8 innodb_cluster
20200613 my sql-ha-deployment
OUGLS 2016: Guided Tour On The MySQL Source Code
MySQL for Software-as-a-Service (SaaS)

More from Ivan Ma (11)

PDF
Exploring MySQL Operator for Kubernetes in Python
PDF
20201106 hk-py con-mysql-shell
PDF
20191001 bkk-secret-of inno-db_clusterv1
PDF
20190817 coscup-oracle my sql innodb cluster sharing
PDF
20180420 hk-the powerofmysql8
PDF
20171104 hk-py con-mysql-documentstore_v1
PDF
MySQL InnoDB Cluster and MySQL Group Replication @HKOSC 2017
PDF
What's New in MySQL 8.0 @ HKOSC 2017
PDF
01 demystifying mysq-lfororacledbaanddeveloperv1
PDF
20150110 my sql-performanceschema
PDF
20141011 my sql clusterv01pptx
Exploring MySQL Operator for Kubernetes in Python
20201106 hk-py con-mysql-shell
20191001 bkk-secret-of inno-db_clusterv1
20190817 coscup-oracle my sql innodb cluster sharing
20180420 hk-the powerofmysql8
20171104 hk-py con-mysql-documentstore_v1
MySQL InnoDB Cluster and MySQL Group Replication @HKOSC 2017
What's New in MySQL 8.0 @ HKOSC 2017
01 demystifying mysq-lfororacledbaanddeveloperv1
20150110 my sql-performanceschema
20141011 my sql clusterv01pptx

Recently uploaded (20)

PPTX
Effective_Handling_Information_Presentation.pptx
PDF
Parts of Speech Prepositions Presentation in Colorful Cute Style_20250724_230...
PPTX
Intro to ISO 9001 2015.pptx wareness raising
PPTX
Human Mind & its character Characteristics
PPTX
Tour Presentation Educational Activity.pptx
PPTX
Impressionism_PostImpressionism_Presentation.pptx
PPTX
Presentation for DGJV QMS (PQP)_12.03.2025.pptx
PPTX
Understanding-Communication-Berlos-S-M-C-R-Model.pptx
PDF
Why Top Brands Trust Enuncia Global for Language Solutions.pdf
PPTX
INTERNATIONAL LABOUR ORAGNISATION PPT ON SOCIAL SCIENCE
PDF
Swiggy’s Playbook: UX, Logistics & Monetization
PPTX
fundraisepro pitch deck elegant and modern
PPTX
Emphasizing It's Not The End 08 06 2025.pptx
PPTX
worship songs, in any order, compilation
PPTX
BIOLOGY TISSUE PPT CLASS 9 PROJECT PUBLIC
PPTX
Hydrogel Based delivery Cancer Treatment
DOC
学位双硕士UTAS毕业证,墨尔本理工学院毕业证留学硕士毕业证
PPTX
An Unlikely Response 08 10 2025.pptx
PPTX
Introduction to Effective Communication.pptx
PPTX
Non-Verbal-Communication .mh.pdf_110245_compressed.pptx
Effective_Handling_Information_Presentation.pptx
Parts of Speech Prepositions Presentation in Colorful Cute Style_20250724_230...
Intro to ISO 9001 2015.pptx wareness raising
Human Mind & its character Characteristics
Tour Presentation Educational Activity.pptx
Impressionism_PostImpressionism_Presentation.pptx
Presentation for DGJV QMS (PQP)_12.03.2025.pptx
Understanding-Communication-Berlos-S-M-C-R-Model.pptx
Why Top Brands Trust Enuncia Global for Language Solutions.pdf
INTERNATIONAL LABOUR ORAGNISATION PPT ON SOCIAL SCIENCE
Swiggy’s Playbook: UX, Logistics & Monetization
fundraisepro pitch deck elegant and modern
Emphasizing It's Not The End 08 06 2025.pptx
worship songs, in any order, compilation
BIOLOGY TISSUE PPT CLASS 9 PROJECT PUBLIC
Hydrogel Based delivery Cancer Treatment
学位双硕士UTAS毕业证,墨尔本理工学院毕业证留学硕士毕业证
An Unlikely Response 08 10 2025.pptx
Introduction to Effective Communication.pptx
Non-Verbal-Communication .mh.pdf_110245_compressed.pptx

20161029 py con-mysq-lv3

  • 1. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. | Creating Python application with MySQL High Availability Database Service Ivan Ma ivan-cs.ma@oracle.com 2016-10-29 Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
  • 2. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. | Safe Harbor Statement The following is intended to outline our general product direction. It is intended for information purposes only, and may not be incorporated into any contract. It is not a commitment to deliver any material, code, or functionality, and should not be relied upon in making purchasing decisions. The development, release, and timing of any features or functionality described for Oracle’s products remains at the sole discretion of Oracle. 2
  • 3. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. | Program Agenda 3 MySQL High Availability Intro Python – Connecting to Database Making Query to Database Python – Failover (HA) connection to Database Flask – Web App Sample 1 2 3 4 5
  • 4. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. | Overview • MySQL as Database – Highly Available Configuration and Setup • Python – The Programming Language – Using Framework (e.g. FLASK ) – Database Connection – Query – Row Result Processing – Error Handling
  • 5. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. | Today • Introducing – MySQLGroup Replication – MySQLReplication – MySQLRouter – MySQLInnoDB Cluster • MySQL Connector/Python – Connecting to MySQL – SELECT statements – Looping Result – Executing Stored Procedure – ErrorHandling in Python with MySQL – multi-host connection with MySQL
  • 6. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. | A Quick Walk thru of MySQL HA • MySQL High Availability – Redundancy is the Key • MySQL Replication • MySQL Semi-SyncReplication • MySQL Group Replication • Shared Storage with OS Clustering • MySQL Cluster • Application Connection to MySQL – Connector / Driver • Connector/ Python • Connector / Java • Connector / .NET, PHP, etc…
  • 7. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. | A Quick Walk thru of MySQL HA • MySQL High Availability – Redundancy is the Key • MySQL Replication • MySQL Semi-SyncReplication • MySQL Group Replication (RC) • Shared Storage with OS Clustering – MySQL service • MySQL Cluster • Application Connection to MySQL – Connector / Driver • Connector/ Python • Connector / Java • Connector / .NET, PHP, etc… MySQL Router
  • 8. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. | MySQL Group Replication (Release Candidate) Natively distributed and highly available replica sets
  • 9. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. | MySQL Group Replication: What Does It Provide? • A highly available distributed MySQL database service – Removes the need for manually handling server fail-over – Provides distributed fault tolerance – Enables Active/Active update anywhere setups – Automates reconfiguration (adding/removing nodes, crashes, failures) – Automatically detects and handles conflicts 9
  • 10. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. | MySQL Server: Core • Server calls into the plugin through a generic interface – Most server internals are hidden from the plugin • Plugin interacts with the server through a generic interface – Replication plugin determines the fate of the commit operation through a well defined server interface – The plugin makes use of the relay log infrastructure to inject changes in the receiving server 10 GCS API Replication Plugin Plugin API MySQL Server Group Com. Engine GCS API Replication Plugin Plugin API MySQL Server Group Com. Engine Network
  • 11. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. | MyQL Connector / Python
  • 12. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. | MySQL Connector / Python • To download the Connetor/Python, – https://dev.mysql.com/downloads/connector/python/
  • 13. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. | Connecting MySQL • import mysql.connector • import sys • _pass = '' • if len(sys.argv) > 1 : • _pass = sys.argv[1] • cnx = mysql.connector.connect(user='root', password=_pass, host='127.0.0.1',port=3306, database='mysql') • cnx.close()
  • 14. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. | 14
  • 15. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. | “connection” – MySQLConnection Class • frommysql.connector import (connection) • import sys • _pass=''; • if len(sys.argv) > 1 : • _pass=sys.argv[1] • cnx = connection.MySQLConnection(user='root', password=_pass, host='127.0.0.1',port=3306, database='mysql') • cnx.close()
  • 16. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. | Connection Pooling 16 Implicit Explicit
  • 17. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. | Connecting MySQL using Dictionary config • import mysql.connector • import sys • _pass=''; • if len(sys.argv) > 1 : • _pass=sys.argv[1] • config = { 'user': 'root', 'password': '', 'host': '127.0.0.1', 'database': 'mysql', • 'raise_on_warnings': True, } • cnx = mysql.connector.connect(**config) • cnx.close()
  • 18. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. | Error Handling in Connection (try …. except…finally) • try: • cnx = mysql.connector.connect(user='root', host='127.0.0.1', port=3306, • password=_pass, • database=_db) • print("connect success") • except mysql.connector.Error as err: • if err.errno == errorcode.ER_ACCESS_DENIED_ERROR: • print("Something is wrong with your user name or password") • elif err.errno == errorcode.ER_BAD_DB_ERROR: • print("Database does not exist") • else: • print(err) • finally: • print ("Finally - close connection") • cnx.close()
  • 19. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. | SELECT • cnx = mysql.connector.connect(**config) • operation = “select ……. from …..; select …. from ….” • cursor = cnx.cursor() • try: • …… • except mysql.connector.Error as err: • print(err.msg) • cursor.close() • cnx.close() 19 for result in cursor.execute(operation, multi=True): if result.with_rows: print("rows producted by statement '{}':".format(result.statement)) row = cursor.fetchone() while row: print(row) row = cursor.fetchone() else: print("Number of rows affeted by statement '{}':{}".format(result.statement, result.rowcount))
  • 20. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. | Failover Connection Property • operation ='SELECT @@hostname, @@port, employees.*from employees limit 10‘ • try: • for result in cursor.execute(operation, multi=True): • if result.with_rows: • print("rows producted by statement '{}':".format(result.statement)) • row = cursor.fetchone() • whilerow: • print(row) • row = cursor.fetchone() • else: • print("Number of rows affeted by statement '{}':{}".format(result.statement, result.rowcount)) • except mysql.connector.Error as err: • print(err.msg) • cursor.close() • cnx.close() 20 config = { 'raise_on_warnings': True, 'failover' : [ { 'user': 'root‘, 'password': '‘, 'host': '127.0.0.1‘, 'port': 3306, 'database': 'employees', }, { 'user': 'root‘, 'password': '‘, 'host': '127.0.0.1‘, 'port': 3306, 'database': 'employees',} ] } cnx = mysql.connector.connect(**config)
  • 21. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. | Program Agenda 21 MySQL High Availability Intro Python – Connecting to Database Making Query to Database Python – Failover (HA) connection to Database Flask – Web App Sample 1 2 3 4 5
  • 22. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. | 22
  • 23. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. | Home Page with Flask • from flask import Flask, render_template, request, json • importmysql.connector • from mysql.connector import errorcode • app = Flask(__name__) • @app.route("/") • @app.route("/main") • defmain(): • return render_template('03-index.html') 23 config = { 'user': 'root', 'password': '', 'host': '127.0.0.1', 'port': 3316, 'database': 'pycon2016hk', 'raise_on_warnings': True, }
  • 24. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. | Register – Calling Stored Procedure • @app.route("/Register", methods=["POST","GET"]) • def register(): • try: • _name = request.form['inputName'] • _password = request.form['inputPassword'] • # validate the values • if _name and _password: • • else: • return '<p>Please Enter the required fields!!</p>' • except Exception as e: • return '<p><span>DB Error' + str(e) +'</spand></p>' • finally: ****************************************** 24 conn = mysql.connector.connect(**config) cursor = conn.cursor() cursor.callproc("sp_user",[ _name, _password]) if len(list(cursor.stored_results())) is 0: conn.commit() return 'Message:User created successfully!‘ else: data = [] for result in cursor.stored_results(): data.append(str(result.fetchall())) return '<p><span>Error:' + str(data) + '</span></p>'
  • 25. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. | THANK YOU! 25