MySQLdb安装|Centos 7 下关联 python 和 MariaDB or MySQL

              **Edited by 蘑菇@HDUMaker**

Overview

系统配置:CentOS 7
python:Python 2.7.5
Mariadb:10.0.20-MariaDB MariaDB Server

进入python下输入 import MySQLdb

Python 2.7.5 (default, Jun 24 2015, 00:41:19)
[GCC 4.8.3 20140911 (Red Hat 4.8.3-9)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import MySQLdb

回收到如下报错

ImportError: No module named MySQLdb

所以需要安装MySQLdb库,在此之前需要做如下配置

Dependencies

安装python-devel

ERROR: MySQLdb: Python.h: No such file or directory

由于MySQLdb是用c写的所以需要python-devel包

[root@iZ236xzsl93Z /]# yum -y install build-essential python-dev
Loaded plugins: langpacks
No package build-essential available.
No package python-dev available.
Error: Nothing to do

然而并不可以 ,因为在yum下dev并不叫这个名字╮(╯▽╰)╭
如下是身份证上的名字

For CentOS:

#> yum install mysql-devel

For openSUSE:


#> zypper install libmysqlclient-devel

For Debian-based systems/Ubuntu:


#> apt-get install libmysqlclient-dev

安装mysql-devel

即便是安装MySQL-python后我还是会遇到这个报错

mysql_config: command not found

#Error
sh: mysql_config: command not found
Command python setup.py egg_info failed with error code 1 in /tmp/pip-build-bIrQHo/MySQL-python
Storing debug log for failure in /root/.pip/pip.log

解决方法:安装

[root@iZ236xzsl93Z ~]# yum install mysql-devel

最终显示:

Installed:
  MariaDB-devel.x86_64 0:10.0.20-1.el7.centos
Complete!

【注】因为我安装的是MariaDB所以这里是MariaDB-devel

放在后面解决>>>

ImportError: No module named mysql.*

... import mysql.connector as mariadb
Traceback (most recent call last):
  File "", line 2, in 
ImportError: No module named mysql.connector

Installation

 #>yum install MySQL-python

安装了MySQL-python 跟MariaDB的shared文件

Install  1 Package (+1 Dependent package)
Total download size: 1.3 M
Installed size: 6.2 M
Is this ok [y/d/N]: y
Downloading packages:
(1/2): MySQL-python-1.2.3-11.el7.x86_64.rpm
(2/2): MariaDB-10.0.20-centos7-x86_64-shared.rpm

最后打开python测试下,能不能用

貌似还是不可以╮(╯▽╰)╭ 为啥呢 想不通@@@@@@@
接着试错…

下载MySQL-python-1.2.4b5.tar.gz

wget https://pypi.python.org/packages/source/M/MySQL-python/MySQL-python-1.2.4b5.tar.gz#md5=2d760ee948aff4f50d01afdf8afff48c

解压安装包 安装

[root@~]tar -zxvf MySQL-python-1.2.4b5 
[root@~]cd MySQL-python-1.2.4b5
[root@~ MySQL-python-1.2.4b5]# python setup.py build
[root@~MySQL-python-1.2.4b5]# python setup.py install

然而神奇的事情发生了 ,竟然能用了

>>> import MySQLdb
>>> db =  MySQLdb.connect("localhost","root","","test")
>>> cursor =  db.cursor()
>>> cursor.execute("SELECT VERSION()")

>>> data = cursor.fetchone()
>>> print "Database version : %s"%data
Database version : 10.0.20-MariaDB
>>> db.close()

成功了O(∩_∩)O哈!

References

How to connect Python programs to MariaDB
mysql-libmysqlclient
MySQLdb: Python.h: No such file or directory

Related Article

python操作mysql数据库@自强学堂

你可能感兴趣的:(MySQLdb安装|Centos 7 下关联 python 和 MariaDB or MySQL)