Database Reference
In-Depth Information
Python
To use Python withMySQL, you can you use the MySQL Connector/Python. It's written in
Python and needs only the Python libraries to function. It doesn't require any Python mod-
ules besides what's already part of the Python standard library. Nor does it require the
MySQL client library.
Installing
The firstthing you will need to do is install the MySQL Connector/Python on your server.
You can do this by using an installationutility like yum on a Linux system. Python and its
libraries are probably already installed on your server, but you can try installing them at the
same time to be sure. Execute this from the command line:
yum install python python-libs mysql-connector-python
NOTE
This section uses Version 2 of Python, which is still the most common one installed on Linux and Mac
systems at the time of this writing. Version 3 is becoming popular, and requires minor syntax changes, but
you can read about it elsewhere. If you want to use Version 3, and perhaps another library for connecting
Python to MySQL, you will probably need only minor changes to the code shown in this section.
Once you have the connector installed on your server, you can then write and run a Python
program to connect to MySQL and query databases. For the example in this section, sup-
pose the database administrator in charge of managing MySQL users has asked us to write
a program that would give him a list of user accounts and privileges for each. Let's go
through a very simple program to do this.
Connecting to MySQL
To query a databasewith Python, we will need to establish a connection with MySQL.
Here is the beginning part of a Python program to do this:
#!/usr/bin/python
import mysql.connector
config = {
'user' : 'admin_granter' ,
'password' : 'avocet_123' ,
'host' : 'localhost' ,
'database' : 'rookery'
Search WWH ::




Custom Search