python模块 mysql-python安装(在ubuntu系统下)

直接运行如下命令

sudo pip install MySQL-python

报如下错误

xxx@ubuntu:~$ sudo pip install MySQL-python
Downloading/unpacking MySQL-python
  Downloading MySQL-python-1.2.5.zip (108kB): 108kB downloaded
  Running setup.py (path:/tmp/pip_build_root/MySQL-python/setup.py) egg_info for package MySQL-python
    sh: 1: mysql_config: not found
    Traceback (most recent call last):
      File "<string>", line 17, in <module>
      File "/tmp/pip_build_root/MySQL-python/setup.py", line 17, in <module>
        metadata, options = get_config()
      File "setup_posix.py", line 43, in get_config
        libs = mysql_config("libs_r")
      File "setup_posix.py", line 25, in mysql_config
        raise EnvironmentError("%s not found" % (mysql_config.path,))
    EnvironmentError: mysql_config not found
    Complete output from command python setup.py egg_info:
    sh: 1: mysql_config: not found

解决方案是:

安装python-dev
sudo apt-get install python-dev

然后再安装

sudo apt-get install libmysqlclient-dev

最后安装

sudo pip install MySQL-python

这样就成功了。

下面是测试代码:

import MySQLdb
try:
    conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='root',db='mydb',port=3306)
    cur=conn.cursor()
    cur.execute('insert into test values(0,"x0")')
    conn.commit()
    cur.close()
    conn.close()
    print "finish insert direct"
except MySQLdb.Error,e:
    print e.args[1]
原文地址:https://www.cnblogs.com/51kata/p/5406468.html