Python: Difference between revisions

From Leo's Notes
This page was last edited on 22 April 2013, at 05:01.
No edit summary
Line 20: Line 20:
  yum instal MySQL-python
  yum instal MySQL-python


To use it, import <code>_mysql</code>
To use it, import <code>_mysql</code>, or you can use the <code>MySQLdb</code> wrapper. Basically, to fetch something, we can now do:


import MySQLdb as mdb # Wraps _mysql
import sys
con = mdb.connect("search", "lyricslive", "lyricslive", "lyricslive")
with con:
    cur = con.cursor(mdb.cursors.DictCursor)
    cur.execute("SELECT * FROM lyric LIMIT 1")
    results = cur.fetchall()
    for record in results:
        print record["lyric"]
The above is analogous to <code><?php $result = mysql_fetch_array($handle); ?></code>. If we take out <code>mdb.cursors.DictCursor</code>, the records will not be in a dictionary but rather fields.


[[Category:Code]]
[[Category:Code]]

Revision as of 05:01, 22 April 2013

This is a page dedicated to me learning python.

No module named ez_setup

While trying to install a package, you get:

Traceback (most recent call last):
  File "setup.py", line 12, in <module>
    from ez_setup import use_setuptools
ImportError: No module named ez_setup

On CentOS (or other RHEL derivatives), run:

yum install python-setuptools

On other platforms, it's probably named python-distutils


MySQL

To install the MySQL connector:

yum instal MySQL-python

To use it, import _mysql, or you can use the MySQLdb wrapper. Basically, to fetch something, we can now do:


import MySQLdb as mdb # Wraps _mysql
import sys

con = mdb.connect("search", "lyricslive", "lyricslive", "lyricslive")

with con:
    cur = con.cursor(mdb.cursors.DictCursor)
    cur.execute("SELECT * FROM lyric LIMIT 1")
    results = cur.fetchall()

    for record in results:
        print record["lyric"]

The above is analogous to <?php $result = mysql_fetch_array($handle); ?>. If we take out mdb.cursors.DictCursor, the records will not be in a dictionary but rather fields.