SlideShare a Scribd company logo
USING MYSQL THROUGH PYTHON

                                   MYSQLDB


                                  TAYLOR REDD




                                 1. Intoduction
   This tutorial will help make you familiar with the basic steps needed to access a
MySQL database through python. It will go over downloading, installing, and using
MySQLdb. This is the package that python uses to access MySQL. The hardest
part to MySQLdb is installing it. Once installed it is very easy to use as long
as you know how to use MySQL. While most steps, if not all, in the installation
tutorial should work on Windows, this tutorial is designed for Mac OS X 10.5.
Using MySQLdb in python is the same for any platform.

                   2. Downloading/Installing MySQLdb
Step 1. Download
     • Go to http://sourceforge.net/projects/mysql-python
     • Click Download in the green box to the right.
     • Click download for mysql-python version 1.2.2
     • Download the appropriate file. (for Mac OS X 10.5 users this will be the
       MySQL-python-1.2.2.tar.gz file
Step 2. Unpack File
     • Find the location of file and unpack it by double clicking it.
Step 3. Change site.cfg
     • Find mysql config
         – Open Terminal and change directories to /usr/local/mysql (type cd
            /usr/local/mysql)
         – Type -R — less
         – Find mysql config (This should be in bin/)
         – cd bin/
         – Confirm mysql config is in this directory by typing “ls” and finding
            mysql config
         – Find what directory you’re in by typing “pwd”. This should be output
            /usr/local/mysql/bin
     • Open site.cfg (This will be in the unpacked folder MySQL-python-1.2.2
     • Uncomment the line that says “mysql config = /usr/local/bin/mysql config”
       and change it so that it says mysql config = /usr/local/mysql/bin/mysql config
       (or whatever directory you were in when you typed pwd)
     • Save and close this file
Step 4. Edit mysql.c
                                         1
2                                TAYLOR REDD


     • Remove the following lines
         – #ifndef uint
         – #define uint unsigned int
         – #endif
     • Change the following
         – uint port = MySQL PORT;
         – uint client flag = 0;
     • To:
         – unsigned int port = MySQL PORT;
         – unsigned int client flag = 0;
Step 5. Installing MySQLdb
     • Open a Terminal window
     • Change directories to the MySQL-python-1.2.2
     • Enter “sudo python setup.py build” (you will probably be prompted to
       enter a password)
     • Enter “sudo python setup.py install”
     • Start python
     • Enter “import MySQLdb

                             3. Using MySQLdb
Step 6. Connect to the Database
     • You can connect to the database using the python command MySQLdb.connect()
       and the following parameters.
         – host: name of system where MySQL is running. Default is localhost.
         – user: user id. Default value = current user
         – passwd: password for user id. No default value
         – db: database that you want to connect to. No default value
         – port: port where server is on. Default value is 3306
     • Example: db=MySQLdb.connect(host=”localhost”, user=”root”, db=”mystudents”)
     • Now db is our connection to the database.
     • Note: Anything left out of the command such as host or user will just use
       the default value.
Step 7. Creating a Cursor
     • Creating a cursor enables you to make queries through python. It is also
       where data is kept once a query is executed.
     • Creating a cursor can be done with the following line:
          – cursor=db.cursor()
     • To make a query just use cursor.execute() with the MySQL query.
     • Examples:
          – cursor.execute(“select * from people”)
          – cursor.execute(“““INSERT INTO people (f name, m name, l name,
            age) VALUES (“John”, “I don’t know him”, “Dow”, 66))””
     • To use variables stored in python you must use place holders. For example,
       if we had a “John” stored as a python variable fname, “I don’t know him”
       as mname, and “Dow” as lname our execute statement would look like:
          – cursor.execute(“INSERT INTO people(f name, m name, l name, age)
            VALUES (%s, %s, %s, %s)”, (fname, mname, lname, age))
USING MYSQL THROUGH PYTHON                              MYSQLDB             3


Step 8. Using fetchone() and fetchall()
     • fetchone(): returns one row of python tuple. It returns the next tuple not
       already returned.
     • fetchall(): returns a tuple of tuples. Basically, a list of all the rows.
     • Example: cursor.execute(”select * from people”)
          – row=cursor.fetchone() - sets row to the first entry in people
            row=cursor.fetchone() - sets row to the next entry in people.
          – rows=cursor.fetchall() - sets rows as a list of all the entries. rows[0][0]
            returns the first name of the first person.

More Related Content

PDF
Joy of Unix
PPT
New kid on the block node.js
PDF
Vagrant勉強会 チュートリアル編
PDF
MongoDB Database Replication
PPTX
Mule esb object_to_json
PPTX
Muleesbobjecttojson
PPTX
Mule esb json_to_object
PPTX
vSRX automation 3: NAT
Joy of Unix
New kid on the block node.js
Vagrant勉強会 チュートリアル編
MongoDB Database Replication
Mule esb object_to_json
Muleesbobjecttojson
Mule esb json_to_object
vSRX automation 3: NAT

What's hot (20)

PDF
Archlinux install
PPTX
MongoDB Replication (Dwight Merriman)
PDF
Managing PostgreSQL with Ansible - FOSDEM PGDay 2016
PPTX
Puppet overview
PDF
리눅스 간단 강의 5강
PDF
Cassandra summit 2013 - DataStax Java Driver Unleashed!
PPTX
От sysV к systemd
PDF
Nginx cache api delete
PPTX
Mule esb - How to convert from Json to Object in 5 minutes
PDF
Javantura v2 - Replication with MongoDB - what could go wrong... - Philipp Krenn
PDF
Ast transformations
PDF
Introduction to Rust
PDF
Custom Altcoin - Custom Altcoin Creation Services | makecryptocoin
PPTX
Redis fundamental
PDF
What's New in Swift 4
PDF
Searched gems which supports only ruby 2.6
PDF
Mastering the MongoDB Shell
PDF
Java Week9(A) Notepad
PPTX
Codable routing
PPTX
Mule esb How to convert from Object to Json in 5 minutes
Archlinux install
MongoDB Replication (Dwight Merriman)
Managing PostgreSQL with Ansible - FOSDEM PGDay 2016
Puppet overview
리눅스 간단 강의 5강
Cassandra summit 2013 - DataStax Java Driver Unleashed!
От sysV к systemd
Nginx cache api delete
Mule esb - How to convert from Json to Object in 5 minutes
Javantura v2 - Replication with MongoDB - what could go wrong... - Philipp Krenn
Ast transformations
Introduction to Rust
Custom Altcoin - Custom Altcoin Creation Services | makecryptocoin
Redis fundamental
What's New in Swift 4
Searched gems which supports only ruby 2.6
Mastering the MongoDB Shell
Java Week9(A) Notepad
Codable routing
Mule esb How to convert from Object to Json in 5 minutes
Ad

Viewers also liked (8)

PDF
Pydbapi
PDF
Handson Python
PDF
Www Kitebird Com Articles Pydbapi Html Toc 1
PDF
Python 3 Days
PDF
Ajax Tags Advanced
PDF
Python Tutorial
PDF
Html5 Cheat Sheet
PDF
Tutorial Python
Pydbapi
Handson Python
Www Kitebird Com Articles Pydbapi Html Toc 1
Python 3 Days
Ajax Tags Advanced
Python Tutorial
Html5 Cheat Sheet
Tutorial Python
Ad

Similar to My Sq Ldb Tut (20)

PPTX
PYTHON_DATABASE_CONNECTIVITY_for_class_12.pptx
PPTX
python db connection samples and program
PPTX
Pyhton with Mysql to perform CRUD operations.pptx
PPTX
PythonDatabaseAPI -Presentation for Database
PPTX
PYTHON_DATABASE_CONNECTIVITY.pptxPYTHON_DATABASE
PDF
Python my sql database connection
PPTX
unit-5 SQL 1 creating a databse connection.pptx
PDF
MySQL for Python_ Nho Vĩnh Share.pdf
PPTX
Database connectivity in python
PPTX
Interfacing python to mysql (11363255151).pptx
PDF
AmI 2015 - Databases in Python
PPTX
Chapter 6 Interface Python with MYSQL.pptx
PDF
Interface Python with MySQL.pdf
PDF
Python And My Sq Ldb Module
PPTX
Interface Python with MySQLwedgvwewefwefwe.pptx
PPTX
interface with mysql.pptx
PDF
BITS: Introduction to MySQL - Introduction and Installation
PPTX
Python Programming Part 8 - MYSQL.pptx
PDF
python-mysql connectivity (1).pdf
PYTHON_DATABASE_CONNECTIVITY_for_class_12.pptx
python db connection samples and program
Pyhton with Mysql to perform CRUD operations.pptx
PythonDatabaseAPI -Presentation for Database
PYTHON_DATABASE_CONNECTIVITY.pptxPYTHON_DATABASE
Python my sql database connection
unit-5 SQL 1 creating a databse connection.pptx
MySQL for Python_ Nho Vĩnh Share.pdf
Database connectivity in python
Interfacing python to mysql (11363255151).pptx
AmI 2015 - Databases in Python
Chapter 6 Interface Python with MYSQL.pptx
Interface Python with MySQL.pdf
Python And My Sq Ldb Module
Interface Python with MySQLwedgvwewefwefwe.pptx
interface with mysql.pptx
BITS: Introduction to MySQL - Introduction and Installation
Python Programming Part 8 - MYSQL.pptx
python-mysql connectivity (1).pdf

More from AkramWaseem (12)

PDF
Mseduebookexcitinglearningweb Final 120914022330 Phpapp02
PDF
Xml Messaging With Soap
PDF
Xhtml Basics
PDF
Uml Tutorial
PDF
Xhtml Basics
PDF
Ascii Table Characters
PDF
Scripts Python Dbapi
PDF
Random And Dynamic Images Using Python Cgi
PDF
Internet Programming With Python Presentation
PDF
PDF
Docs Python Org Howto Webservers Html
PDF
Tutor Py
Mseduebookexcitinglearningweb Final 120914022330 Phpapp02
Xml Messaging With Soap
Xhtml Basics
Uml Tutorial
Xhtml Basics
Ascii Table Characters
Scripts Python Dbapi
Random And Dynamic Images Using Python Cgi
Internet Programming With Python Presentation
Docs Python Org Howto Webservers Html
Tutor Py

My Sq Ldb Tut

  • 1. USING MYSQL THROUGH PYTHON MYSQLDB TAYLOR REDD 1. Intoduction This tutorial will help make you familiar with the basic steps needed to access a MySQL database through python. It will go over downloading, installing, and using MySQLdb. This is the package that python uses to access MySQL. The hardest part to MySQLdb is installing it. Once installed it is very easy to use as long as you know how to use MySQL. While most steps, if not all, in the installation tutorial should work on Windows, this tutorial is designed for Mac OS X 10.5. Using MySQLdb in python is the same for any platform. 2. Downloading/Installing MySQLdb Step 1. Download • Go to http://sourceforge.net/projects/mysql-python • Click Download in the green box to the right. • Click download for mysql-python version 1.2.2 • Download the appropriate file. (for Mac OS X 10.5 users this will be the MySQL-python-1.2.2.tar.gz file Step 2. Unpack File • Find the location of file and unpack it by double clicking it. Step 3. Change site.cfg • Find mysql config – Open Terminal and change directories to /usr/local/mysql (type cd /usr/local/mysql) – Type -R — less – Find mysql config (This should be in bin/) – cd bin/ – Confirm mysql config is in this directory by typing “ls” and finding mysql config – Find what directory you’re in by typing “pwd”. This should be output /usr/local/mysql/bin • Open site.cfg (This will be in the unpacked folder MySQL-python-1.2.2 • Uncomment the line that says “mysql config = /usr/local/bin/mysql config” and change it so that it says mysql config = /usr/local/mysql/bin/mysql config (or whatever directory you were in when you typed pwd) • Save and close this file Step 4. Edit mysql.c 1
  • 2. 2 TAYLOR REDD • Remove the following lines – #ifndef uint – #define uint unsigned int – #endif • Change the following – uint port = MySQL PORT; – uint client flag = 0; • To: – unsigned int port = MySQL PORT; – unsigned int client flag = 0; Step 5. Installing MySQLdb • Open a Terminal window • Change directories to the MySQL-python-1.2.2 • Enter “sudo python setup.py build” (you will probably be prompted to enter a password) • Enter “sudo python setup.py install” • Start python • Enter “import MySQLdb 3. Using MySQLdb Step 6. Connect to the Database • You can connect to the database using the python command MySQLdb.connect() and the following parameters. – host: name of system where MySQL is running. Default is localhost. – user: user id. Default value = current user – passwd: password for user id. No default value – db: database that you want to connect to. No default value – port: port where server is on. Default value is 3306 • Example: db=MySQLdb.connect(host=”localhost”, user=”root”, db=”mystudents”) • Now db is our connection to the database. • Note: Anything left out of the command such as host or user will just use the default value. Step 7. Creating a Cursor • Creating a cursor enables you to make queries through python. It is also where data is kept once a query is executed. • Creating a cursor can be done with the following line: – cursor=db.cursor() • To make a query just use cursor.execute() with the MySQL query. • Examples: – cursor.execute(“select * from people”) – cursor.execute(“““INSERT INTO people (f name, m name, l name, age) VALUES (“John”, “I don’t know him”, “Dow”, 66))”” • To use variables stored in python you must use place holders. For example, if we had a “John” stored as a python variable fname, “I don’t know him” as mname, and “Dow” as lname our execute statement would look like: – cursor.execute(“INSERT INTO people(f name, m name, l name, age) VALUES (%s, %s, %s, %s)”, (fname, mname, lname, age))
  • 3. USING MYSQL THROUGH PYTHON MYSQLDB 3 Step 8. Using fetchone() and fetchall() • fetchone(): returns one row of python tuple. It returns the next tuple not already returned. • fetchall(): returns a tuple of tuples. Basically, a list of all the rows. • Example: cursor.execute(”select * from people”) – row=cursor.fetchone() - sets row to the first entry in people row=cursor.fetchone() - sets row to the next entry in people. – rows=cursor.fetchall() - sets rows as a list of all the entries. rows[0][0] returns the first name of the first person.