2013年7月24日水曜日

Ubuntu 12.04 LTSにMySQL for Python 1.2.3をインストール

PythonからMySQLにアクセスするためのライブラリ。

任意のフォルダにソースコードをダウンロードして展開。
$ wget http://sourceforge.net/projects/mysql-python/files/mysql-python/1.2.3/MySQL-python-1.2.3.tar.gz
$ tar xvzf MySQL-python-1.2.3.tar.gz
$ cd MySQL-python-1.2.3

ビルドする前に、READMEを参考に、
必要なライブラリのインストールと、site.cfgの編集を行う。
$ sudo apt-get install python-setuptools
$
$ # mysql_configのパスを
$ # mysql_config
$ vi site.cfg
...
# The path to mysql_config.
# Only use this if mysql_config is not on your PATH, or you have some weird
# setup that requires it.
mysql_config = /opt/mysql/server-5.6/bin/mysql_config
...
$

準備ができたらビルドしてインストール。
$ python setup.py build
$ sudo python setup.py install
...
Installed /usr/local/lib/python2.7/dist-packages/MySQL_python-1.2.3-py2.7-linux-x86_64.egg
Processing dependencies for MySQL-python==1.2.3
Finished processing dependencies for MySQL-python==1.2.3
$

最後に、ここ を参考にコードを書いて、MySQLにアクセスできることを確認。
$ mysql -u root -p
Enter password:
...
mysql> create database test_python;
Query OK, 1 row affected (0.00 sec)

mysql> use test_python;
Database changed
mysql> create table test(
    -> id int,
    -> value text,
    -> primary key(id));
Query OK, 0 rows affected (0.04 sec)

mysql> insert into test values(1, "sample text");
Query OK, 1 row affected (0.01 sec)

mysql>

>>> import MySQLdb
>>> conn = MySQLdb.connect(db="test_python", host="127.0.0.1", port=3306, user="root", passwd="xxx")
>>> cur = conn.cursor()
>>> cur.execute("insert into test values (2, 'python text')")
1L
>>> cur.execute("select * from test")
2L
>>> rows = cur.fetchall()
>>> for row in rows:
        print row


(1L, 'sample text')
(2L, 'python text')
>>> cur.close()
>>> conn.commit()
>>> conn.close()
>>>

0 件のコメント:

コメントを投稿