よーぐるとのブログ

技術ネタを中心。私的なことを徒然と綴っていきます。

PythonでMySQL(Mac,Ubuntu)

Mini Tips.

MySQL-pythonを使用します.

MySQLdb User's Guide

Mac(Yosemite)

pipでインストールするだけ

pip install MySQL-python

Ubuntu(14.04)

こちらも同様

sudo pip install MySQL-python

と思ったらなにやらエラーが

EnvironmentError: mysql_config not found

----------------------------------------
Cleaning up...
Command python setup.py egg_info failed with error code 1 in /tmp/pip_build_fukuoka/MySQL-python
Storing debug log for failure in /home/fukuoka/.pip/pip.log

libmysqlclient-devがないらしい

sudo apt-get install libmysqlclient-dev
sudo pip install MySQL-python

実行テスト

次のようなテーブルをサンプルとして扱います

mysql> desc goods;
+-------+-------------+------+-----+---------+----------------+
| Field | Type        | Null | Key | Default | Extra          |
+-------+-------------+------+-----+---------+----------------+
| id    | int(11)     | NO   | PRI | NULL    | auto_increment |
| name  | varchar(10) | YES  | MUL | NULL    |                |
+-------+-------------+------+-----+---------+----------------+

mysql> select * from goods;
+----+-------+
| id | name  |
+----+-------+
|  2 | chair |
|  1 | desk  |
|  3 | pc    |
+----+-------+
"""mysql_test.py"""
# -*- coding: utf-8 -*-
import MySQLdb
connection = MySQLdb.connect(db="test",user="goods")

cursor = connection.cursor()
sql = "select * from goods"
cursor.execute(sql)

# 1行だけ取得
first_row = cursor.fetchone()
print first_row
print "=" * 10

# (残り全行取得)
result = cursor.fetchall()
for row in result:
    print row

cursor.close()
connection.close()

実行結果

python mysql_test.py
(2L, 'chair')
==========
(1L, 'desk')
(3L, 'pc')