SlideShare ist ein Scribd-Unternehmen logo
1 von 3
Downloaden Sie, um offline zu lesen
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.

Weitere ähnliche Inhalte

Was ist angesagt?

MongoDB Replication (Dwight Merriman)
MongoDB Replication (Dwight Merriman)MongoDB Replication (Dwight Merriman)
MongoDB Replication (Dwight Merriman)
MongoSF
 
Cassandra summit 2013 - DataStax Java Driver Unleashed!
Cassandra summit 2013 - DataStax Java Driver Unleashed!Cassandra summit 2013 - DataStax Java Driver Unleashed!
Cassandra summit 2013 - DataStax Java Driver Unleashed!
Michaël Figuière
 
Searched gems which supports only ruby 2.6
Searched gems which supports only ruby 2.6Searched gems which supports only ruby 2.6
Searched gems which supports only ruby 2.6
Maki Toshio
 

Was ist angesagt? (20)

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

Andere mochten auch

Andere mochten auch (8)

Pydbapi
PydbapiPydbapi
Pydbapi
 
Handson Python
Handson PythonHandson Python
Handson Python
 
Www Kitebird Com Articles Pydbapi Html Toc 1
Www Kitebird Com Articles Pydbapi Html Toc 1Www Kitebird Com Articles Pydbapi Html Toc 1
Www Kitebird Com Articles Pydbapi Html Toc 1
 
Python 3 Days
Python  3 DaysPython  3 Days
Python 3 Days
 
Ajax Tags Advanced
Ajax Tags AdvancedAjax Tags Advanced
Ajax Tags Advanced
 
Python Tutorial
Python TutorialPython Tutorial
Python Tutorial
 
Html5 Cheat Sheet
Html5 Cheat SheetHtml5 Cheat Sheet
Html5 Cheat Sheet
 
Tutorial Python
Tutorial PythonTutorial Python
Tutorial Python
 

Ähnlich wie My Sq Ldb Tut

Interfacing python to mysql (11363255151).pptx
Interfacing python to mysql (11363255151).pptxInterfacing python to mysql (11363255151).pptx
Interfacing python to mysql (11363255151).pptx
cavicav231
 
Apache ant
Apache antApache ant
Apache ant
koniik
 
Python And My Sq Ldb Module
Python And My Sq Ldb ModulePython And My Sq Ldb Module
Python And My Sq Ldb Module
AkramWaseem
 

Ähnlich wie My Sq Ldb Tut (20)

Dbdeployer, the universal installer
Dbdeployer, the universal installerDbdeployer, the universal installer
Dbdeployer, the universal installer
 
Dbdeployer
DbdeployerDbdeployer
Dbdeployer
 
Test complex database systems in your laptop with dbdeployer
Test complex database systems in your laptop with dbdeployerTest complex database systems in your laptop with dbdeployer
Test complex database systems in your laptop with dbdeployer
 
20141011 mastering mysqlnd
20141011 mastering mysqlnd20141011 mastering mysqlnd
20141011 mastering mysqlnd
 
Interfacing python to mysql (11363255151).pptx
Interfacing python to mysql (11363255151).pptxInterfacing python to mysql (11363255151).pptx
Interfacing python to mysql (11363255151).pptx
 
Node.js
Node.jsNode.js
Node.js
 
Database connectivity in python
Database connectivity in pythonDatabase connectivity in python
Database connectivity in python
 
Lab Manual Combaring Redis with Relational
Lab Manual Combaring Redis with RelationalLab Manual Combaring Redis with Relational
Lab Manual Combaring Redis with Relational
 
Python and Oracle : allies for best of data management
Python and Oracle : allies for best of data managementPython and Oracle : allies for best of data management
Python and Oracle : allies for best of data management
 
BDM32: AdamCloud Project - Part II
BDM32: AdamCloud Project - Part IIBDM32: AdamCloud Project - Part II
BDM32: AdamCloud Project - Part II
 
4 docker small_web_micro_services
4 docker small_web_micro_services4 docker small_web_micro_services
4 docker small_web_micro_services
 
Hands-on Lab - Combaring Redis with Relational
Hands-on Lab - Combaring Redis with RelationalHands-on Lab - Combaring Redis with Relational
Hands-on Lab - Combaring Redis with Relational
 
Multiple instances on linux
Multiple instances on linuxMultiple instances on linux
Multiple instances on linux
 
Apache ant
Apache antApache ant
Apache ant
 
Mysqlnd uh
Mysqlnd uhMysqlnd uh
Mysqlnd uh
 
Mysql ppt
Mysql pptMysql ppt
Mysql ppt
 
PythonDatabaseAPI -Presentation for Database
PythonDatabaseAPI -Presentation for DatabasePythonDatabaseAPI -Presentation for Database
PythonDatabaseAPI -Presentation for Database
 
Python And My Sq Ldb Module
Python And My Sq Ldb ModulePython And My Sq Ldb Module
Python And My Sq Ldb Module
 
Interface python with sql database.pdf
Interface python with sql database.pdfInterface python with sql database.pdf
Interface python with sql database.pdf
 
Python - db.pptx
Python - db.pptxPython - db.pptx
Python - db.pptx
 

Mehr von AkramWaseem

Mseduebookexcitinglearningweb Final 120914022330 Phpapp02
Mseduebookexcitinglearningweb Final 120914022330 Phpapp02Mseduebookexcitinglearningweb Final 120914022330 Phpapp02
Mseduebookexcitinglearningweb Final 120914022330 Phpapp02
AkramWaseem
 
Xml Messaging With Soap
Xml Messaging With SoapXml Messaging With Soap
Xml Messaging With Soap
AkramWaseem
 
Ascii Table Characters
Ascii Table CharactersAscii Table Characters
Ascii Table Characters
AkramWaseem
 
Scripts Python Dbapi
Scripts Python DbapiScripts Python Dbapi
Scripts Python Dbapi
AkramWaseem
 
Random And Dynamic Images Using Python Cgi
Random And Dynamic Images Using Python CgiRandom And Dynamic Images Using Python Cgi
Random And Dynamic Images Using Python Cgi
AkramWaseem
 
Internet Programming With Python Presentation
Internet Programming With Python PresentationInternet Programming With Python Presentation
Internet Programming With Python Presentation
AkramWaseem
 
Docs Python Org Howto Webservers Html
Docs Python Org Howto Webservers HtmlDocs Python Org Howto Webservers Html
Docs Python Org Howto Webservers Html
AkramWaseem
 

Mehr von AkramWaseem (12)

Mseduebookexcitinglearningweb Final 120914022330 Phpapp02
Mseduebookexcitinglearningweb Final 120914022330 Phpapp02Mseduebookexcitinglearningweb Final 120914022330 Phpapp02
Mseduebookexcitinglearningweb Final 120914022330 Phpapp02
 
Xml Messaging With Soap
Xml Messaging With SoapXml Messaging With Soap
Xml Messaging With Soap
 
Xhtml Basics
Xhtml BasicsXhtml Basics
Xhtml Basics
 
Uml Tutorial
Uml TutorialUml Tutorial
Uml Tutorial
 
Xhtml Basics
Xhtml BasicsXhtml Basics
Xhtml Basics
 
Ascii Table Characters
Ascii Table CharactersAscii Table Characters
Ascii Table Characters
 
Scripts Python Dbapi
Scripts Python DbapiScripts Python Dbapi
Scripts Python Dbapi
 
Random And Dynamic Images Using Python Cgi
Random And Dynamic Images Using Python CgiRandom And Dynamic Images Using Python Cgi
Random And Dynamic Images Using Python Cgi
 
Internet Programming With Python Presentation
Internet Programming With Python PresentationInternet Programming With Python Presentation
Internet Programming With Python Presentation
 
Cgi
CgiCgi
Cgi
 
Docs Python Org Howto Webservers Html
Docs Python Org Howto Webservers HtmlDocs Python Org Howto Webservers Html
Docs Python Org Howto Webservers Html
 
Tutor Py
Tutor PyTutor Py
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.