Monday, September 13, 2010

MySQL + Python

I've decided to work with datatables instead of text files.
Guide for ubuntu (9.10, 10.4):
If you have mysql & python installed, you need:
1. Download MySQLdb files from SourceForge
2. tar -xzvf MySQL-python-1.2.3.tar.gz
3. cd MySQL-python-1.2.3
4. python setup.py build
Here there might be some errors:
 File "setup.py", line 5, in
    from setuptools import setup, Extension
ImportError: No module named setuptools

To fix:  sudo apt-get install python-setuptools python-dev libmysqlclient15-dev
or EnvironmentError: mysql_config not found
To fix: export PATH=$PATH:/usr/local/mysql/bin
5. Again: python setup.py build
6. sudo python setup.py install
7. Check: python
>>> import MySQLdb

Connect to MySQL using bash:
mysql -h localhost -u root -p

Create database: create database my_db;


Script example:
import MySQLdb

conn = MySQLdb.connect (host = "localhost",
                         user = "root",
                         passwd = "my_ps",
                         db = "my_db")
cursor = conn.cursor ()
cursor.execute ("SELECT VERSION()")
row = cursor.fetchone ()
print "server version:", row[0]
cursor.close ()
conn.close ()

Manual: http://www.kitebird.com/articles/pydbapi.html 

No comments:

Post a Comment