Top Banner
PYTHON AND MYSQL Miquel Camprodon i Masnou Python Meetup Group Barcelona, May 22th 2014
23

BCNPythonMeetup_20140522_Python&MySQL

May 13, 2015

Download

Technology

miquelcm
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: BCNPythonMeetup_20140522_Python&MySQL

PYTHON AND MYSQLMiquel Camprodon i Masnou

Python Meetup Group

Barcelona, May 22th 2014

Page 2: BCNPythonMeetup_20140522_Python&MySQL

ABOUT THIS TALK

We will see how to interact

from Python

to a relational DB: MySQL

Examples on a Ubuntu 12.04

Page 3: BCNPythonMeetup_20140522_Python&MySQL

WHO AM I?

Miquel Camprodon i Masnou

Mathematician and computer engineer

Working as a data analyst and programmer

Working at: Kernel Analytics

Barcelona

Data analysis

Page 4: BCNPythonMeetup_20140522_Python&MySQL

WHY MYSQL?

Not the most glamorous database

Still the most used open source database

Easy to install, configure, and interact with

A market standard

Available in many hostings and cloud environments

Page 5: BCNPythonMeetup_20140522_Python&MySQL

MYSQL CHARACTERISTICS

Open source RDBMS owned by Oracle

Two storage engines: MyISAM, InnoDB

< 5.5, MyISAM the default storage Not support for ACID transactions Not support Referential Integrity Not support for Crash recovery Better performance on SELECTS

>= 5.5, InnoDB the default storage ACID transactions, RI, Crash recovery Lower performance on SELECT statements

Page 6: BCNPythonMeetup_20140522_Python&MySQL

INSTALLING MYSQL

Examples on a Ubuntu 12.04

$ sudo apt-get install mysql-server

libmysqlclient-dev python-dev

(Asks for a password for the MySQL root account)

Page 7: BCNPythonMeetup_20140522_Python&MySQL

CREATE A NEW DATABASE

$ mysql –u root -p

mysql> SET storage_engine=INNODB;

mysql> CREATE DATABASE testdb;

mysql> GRANT ALL PRIVILEGES ON testdb.*

TO ‘testuser’@’localhost’ IDENTIFIED BY

‘pass123’;

mysql> quit;

Page 8: BCNPythonMeetup_20140522_Python&MySQL

PYTHON WITH MYSQL MODULES

_mysql module

Implements the MySQL C API directly.

Not compatible with the Python DB interface.

MySQLdb module

Python wrapper around _mysql

Compatible with the Python DB API

Preferred way of working with MySQL

Page 9: BCNPythonMeetup_20140522_Python&MySQL

CONFIGURING THE PYTHON ENVIRONMENT

Create Virtualenv

$ virtualenv vepymysql

Activate

$ source vepymysql/bin/activate

Install Python MySQL interface

(vepymysql)$ pip install MySQL-python

Page 10: BCNPythonMeetup_20140522_Python&MySQL

EXAMPLES

From MySQL Python Tutorial

Connect to the database

Create and populate a table

Retrieve data

Retrieve data one by one row

Access results by column name

Show column headers

Prepared statements

Page 11: BCNPythonMeetup_20140522_Python&MySQL

EXAMPLES

Connect to the database

import MySQLdb as mdb

con = mdb.connect('localhost', 'testuser', 'pass123', 'testdb');

cur = con.cursor()

cur.execute("SELECT VERSION()")

ver = cur.fetchone()

con.close()

Page 12: BCNPythonMeetup_20140522_Python&MySQL

EXAMPLES

Create and populate a table

import MySQLdb as mdb

con = mdb.connect('localhost', 'testuser', 'pass123', 'testdb');

with con:

cur = con.cursor()

cur.execute("DROP TABLE IF EXISTS Writers")

cur.execute("CREATE TABLE Writers(Id INT PRIMARY KEY AUTO_INCREMENT, Name VARCHAR(25))")

cur.execute("INSERT INTO Writers(Name) VALUES('Jack L. ')")

cur.execute("INSERT INTO Writers(Name) VALUES('Will S. ')")

Page 13: BCNPythonMeetup_20140522_Python&MySQL

EXAMPLES

Retrieve data

import MySQLdb as mdb

con = mdb.connect('localhost', 'testuser', 'pass123', 'testdb')

with con:

cur = con.cursor()

cur.execute("SELECT * FROM Writers")

rows = cur.fetchall()

Page 14: BCNPythonMeetup_20140522_Python&MySQL

EXAMPLES

Retrieve data one by one row

import MySQLdb as mdb

con = mdb.connect('localhost', 'testuser', 'pass123', 'testdb')

with con:cur = con.cursor()

cur.execute("SELECT * FROM Writers")

for i in range(cur.rowcount):

row = cur.fetchone()

print row[0], row[1]

Page 15: BCNPythonMeetup_20140522_Python&MySQL

EXAMPLES

Access results by column name

import MySQLdb as mdbcon = mdb.connect('localhost', 'testuser', 'pass123', 'testdb')

with con:cur = con.cursor(mdb.cursors.DictCursor)

cur.execute("SELECT * FROM Writers LIMIT 4")

rows = cur.fetchall()

for row in rows:print row["Id"], row["Name"]

Page 16: BCNPythonMeetup_20140522_Python&MySQL

EXAMPLES

Show column headers

import MySQLdb as mdb

con = mdb.connect('localhost', 'testuser', 'pass123', 'testdb')

with con:

cur = con.cursor()

cur.execute("SELECT * FROM Writers LIMIT 5")

rows = cur.fetchall()

desc = cur.description

print "%s %3s" % (desc[0][0], desc[1][0])

for row in rows:

print "%2s %3s" % row

Page 17: BCNPythonMeetup_20140522_Python&MySQL

EXAMPLES

Prepared statementsimport MySQLdb as mdb

con = mdb.connect('localhost', 'testuser', 'pass123', 'testdb')

with con:

cur = con.cursor()

cur.execute("UPDATE Writers SET Name = %s WHERE Id = %s", ("Thomas Mann", "2"))

print "Number of rows updated:", cur.rowcount

cur.execute("UPDATE Writers SET Name = %s WHERE Id = %s",

(("Fiodor Dostovievsky", "3"), ("Dante Alighieri", "4")))

print "Number of rows updated:", cur.rowcount

Page 18: BCNPythonMeetup_20140522_Python&MySQL

TRANSACTION MANAGEMENT

MyISAM Transactions not supported

COMMIT and ROLLBACK do nothing

InnoDB Transaction support

A transaction needs to end with COMMIT or ROLLBACK

Context manager with performs automatically the transaction management.

Page 19: BCNPythonMeetup_20140522_Python&MySQL

EXAMPLES

Transaction management

import MySQLdb as mdb

try: con = mdb.connect('localhost', 'testuser', 'pass123', 'testdb')

cur = con.cursor()

cur.execute("DROP TABLE IF EXISTS Writers")

cur.execute("CREATE TABLE Writers(Id INT PRIMARY KEY, Name VARCHAR(25))")

con.commit()

except mdb.Error, e:

if con:

con.rollback()

print "Error %d: %s" % (e.args[0],e.args[1])

finally:

if con:

con.close()

Page 20: BCNPythonMeetup_20140522_Python&MySQL

EXAMPLES

With context manager

import MySQLdb as mdb

con = mdb.connect('localhost', 'testuser', 'pass123', 'testdb')

with con:

cur = con.cursor()

cur.execute("DROP TABLE IF EXISTS Writers")

cur.execute("CREATE TABLE Writers(Id INT PRIMARY KEY AUTO_INCREMENT, \

Name VARCHAR(25))")

Page 21: BCNPythonMeetup_20140522_Python&MySQL

WHEN TO USE MYSQL?

MySQL easy to learn and work with

If you interact with different customers

If you are looking for a simple hosting

If you are continuing previous work from others

-> Probably you will work with MySQL

If you are starting your project from scratch

-> Think in various options, including MySQL

Page 23: BCNPythonMeetup_20140522_Python&MySQL

Questions?

My e-mail:

[email protected]

THANK YOU!