- Manage MySQL databases
- Manipulate data using SQL queries
- MySQL stored procedures
- Database views
- Triggers
- Querying data, updating data, managing databases and creation of tables
- MySQL dialect
- Installing MySQL, downloading sample data, loading data into MySQL server
-
classicmodels- database- Retailer of scale models of classic cars database
- Contains following business data
- Customers
- Products
- Sales Orders
- Sales Order Line Items
-
how to load sample database into MySQL database server tutorial
-
Test
USE classicmodels; SELECT * FROM customers;
-
-
MySQL Sample Database Schema
- Customers: stores customer's data
- Products: stores a list of scale model cars
- ProductLines: stores a list of product line categories
- Orders: stores sales orders placed by customers
- OrderDetails: stores sales order line items for each sales order
- Payments: stores payments made to customers based on their accounts
- Employees: stores all employee information as well as the organization structure such as who reports to whom
- Offices: stores sales office data
- Use MySQL connector/Python to access MySQL databases
- How to connect to MySQL database
- Perform common database operations
- SELECT
- INSERT
- UPDATE
- DELETE
- How to call MySQL stored procedure from Python
- How to work with MySQL BLOB data
- MySQL Python connector's features
- How to install MySQL Connector/Python in local system
- We need database driver to access MySQL database from Python
- MySQL connector/Python - standard database driver
- Supports almost all features of v 5.7
- Allows conversion of parameter values between Python and MySQL datatypes
- Python datetime and MySQL DATETIME
- Supports MySQL extensions to standard SQL (LIMIT clause)
- Allows compression of data stream between Python and MySQL database server using protocol compression.
- Supports TCP/IP socket and secure TCP/IP connection using SSL
- It is API implemented using pure Python
- No need for client library or module but only standard library
- Supported versions of Python 2.6, 2.7, and 3.3
- MySQL connector/Python - standard database driver
- download
- Install
- Unzip/Untar
- Goto directory
- Run
python setup.py install
-
Open Python3 command line
-
Run the following:
import mysql.connector mysql.connector.connect(host='localhost', database='mysql', user='root', password='')- Output:
<mysql.connector.connection.MySQLConnection object at xxxxx>
- Output:
- New database:
python_mysql-
In workbench
-
MySQL client
CREATE DATABASE python_mysql;
-
- Load Sample data: Python MySQL Sample Database
-
python_mysql_connect1.pyimport mysql.connector from mysql.connector import Error def connect(): """ Connect to MySQL database """ try: conn = mysql.connector.connect(host='localhost', database='python_mysql', user='root', password='secret') if conn.is_connected(): print('Connected to MySQL database') except Error as e: print(e) finally: conn.close() if __name__ == '__main__': connect()mysql.connectorandErrorobjects are imported from MySQL Connector/Python packageconnect()accepts parameters host, database, user, password.- Establishes connection to
python_mysqldatabase and returnsMySQLConnectionobject
- Establishes connection to
is_connected()is used to check connection to MySQL databaseErrorexception is raised if eg:- database server is not available
- database does not exist
- invalid user name or password
close()method ofMySQLConnectioncloses database connection
-
Testing:
python python_mysql_connect1.py
-
A database configuration file
config.ini[mysql] host = localhost database = python_mysql user = root password = -
New module
python_mysql_dbconfig.pyreads database configuration fromconfig.iniand returns dictionaryfrom ConfigParser import ConfigParser def read_db_config(filename='config.ini', section='mysql'): """ Read database configuration file and return a dictionary object :param filename: name of the configuration file :param section: section of database configuration :return: a dictionary of database parameters """ # creation of parser and read ini configuration file parser = ConfigParser() parser.read(filename) # get section, default to mysql db = {} if parser.has_section(section): items = parser.items(section) for item in items: db[item[0]] = item[1] else: raise Exception('{0} not found in the {1} file'.format(section, filename)) return db-
ConfigureParser- Used to read configuration file -
Testing:
from python_mysql_dbconfig import read_db_config read_db_config()
-
-
New module
python_mysql_connect2.pywhich usesMySQLConnectionobject to connect topython_mysqlfrom mysql.connector import MySQLConnection, Error from python_mydql_dbconfig import read_db_config def connect(): """ Connect to MySQL database """ db_config = read_db_config() try: print('Connecting to MySQL database...') conn = MySQLConnection(**db_config) if conn.is_connected(): print('connection established.') else: print('connection failed.') except Error as error: print(error) finally: conn.close() print('Connection closed.') if __name__ == '__main__': connect()MySQLConnection,Errorare imported from MySQL Connector/Python packageread_db_configis imported frompython_mysql_dbconfigmoduleconnect()is used to read database configuration
-
Testing:
python python_mysql_connect2.py
- To query data using MySQL Connector/Python API
fetchone()fetchmany()fetchall()
- Steps:
- Connect to MySQL database and you get
MySQLConnectionobject - Instantiate
MySQLCursorobject fromMySQLConnectionobject - Use cursor to execute a query by calling its
execute()method - Use
fetchone(),fetchmany()orfetchall()method to fetch data from result set - Close the cursor as well as database connection by calling
close()method of corresponding object
- Connect to MySQL database and you get
-
Example:
from mysql.connector import MySQLConnection, Error from python_mysql_dbconfig import read_db_config def query_with_fetchone(): try: dbconfig = read_db_config() conn = MySQLConnection(**dbconfig) cursor = conn.cursor() cursor.execute('SELECT * FROM books') row = cursor.fetchone() while row is not None: print(row) row = cursor.fetchone() except Error as e: print(e) finally: cursor.close() conn.close() if __name__ == '__main__': query_with_getchone()- Connected to db using
MySQLConnectionobject - Instantiated new
MySQLCursorobject fromMySQLConnectionobject - Executed query that selects all rows from
bookstable - Called
fetchone()to fetch next row in result set - Closed connection object by invoking
close()method of corresponding object
- Connected to db using
fetchall()usually used if number of rows is small-
Fetches all rows from database
from mysql.connector import MySQLConnection from python_mysql_dbconfig import read_db_config def query_with_fetchall(): try: dbconfig = read_db_config() conn = MySQLConnection(**dbconfig) cursor = conn.cursor() cursor.execute('SELECT * FROM books') rows = cursor.fetchAll() print('Total rows(s):', cursor.rowcount) for row in rows: print(row) except Error as e: print(e) finally: cursor.close() conn.close() if __name__ == '__main__': query_with_fetchall()- All rows are fetched into memory
-
-
fetchmany()returns next number of rows (n) of result set - allows balance between time and spacedef iter_row(cursor, size=10): while True: rows = cursor.fetchmany(size) if not rows: break for row in rows: yield row def query_with_fetchmany(): try: dbconfig = read_db_config() conn = MySQLConnection(**dbconfig) cursor = conn.cursor() cursor.execute('SELECT * FROM books') for row in iter_row(cursor, 10): print(row) except Error as e: print(e) finally: cursor.close() conn.close()
- Steps to insert rows:
- Connect to MySQL database server by instantiating
MySQLConnectionobject - Initiate
MySQLCursorobject fromMySQLConnectionobject - Execute
INSERTstatement to insert data into intended table - Close database connection
- Connect to MySQL database server by instantiating
- We can insert one or many rows at a time
-
Example: New book into books table
from mysql.connector import MySQLConnection, Error from python_mysql_dbconfig import read_db_config def insert_book(title, isbn): query = 'INSERT INTO books (title, isbn) ' \ 'VALUES (%s, %s)' args = (title, isbn) try: db_config = read_db_config() conn = MySQLConnection(**db_config) cursor = conn.cursor() cursor.execute(query, args) if cursor.lastrowid: print('last insert id', cursor.lastrowid) else: print('last insert id not found') conn.commit() except Error as error: print(error) finally: cursor.close() conn.close() def main(): insert_book('A Sudden Light', '9781439187036') if __name__ == '__main__': main()insert_book()accepts title and isbn- We prepare
INSERTstatement (query) and data (args)- Data is passed as a tuple
- We prepare
commit()- called explicitly to make changes to databaselastrowid- gets the last insert id of AUTO_INCREMENT column- Call
insert_book()and passtitleandisbn
- High Performance MySQL: Optimization, Backups, and Replication
- MySQL Administrator's Bible
- MySQL High Availability: Tools for Building Robust Data Centers
- Effective MySQL Optimizing SQL Statements (Oracle Press)
- Understanding MySQL Internals
- Effective MySQL Backup and Recovery (Oracle Press) (Oracle (McGraw-Hill))
- Head First PHP & MySQL
- MySQL Stored Procedure Programming