Linux系统Python配置MySQL详细教程
欢迎点击右上角关注小编,除了分享技术文章之外还有很多福利,私信学习资料可以领取包括不限于Python实战演练、PDF电子文档、面试集锦、学习资料等。

Linux系统自带Python,且根据系统自带资源来对python配置mysql;安装需要已配置好正确的yum源;
在python未配置mysql的情形下,直接import MySQLdb的提示如下

Linux系统中没有mysql-python的rpm安装包,这个资源需要从网上下载:
目前主流使用Python2.6或Python2.7版本,下载为
MySQL-python-1.2.3c1.tar.gz
下载后上传到Linux机器,放入非中文目录
tar -xf
MySQL-python-1.2.3c1.tar.gz,解压目录如下

在配置python-mysql之前,还需要安装一些依赖项;否则会各种报错缺失

如果命令报错,则表示yum源配置有误,或安装光盘与系统不匹配等,具体请参考Linux下yum源配置教程

如上所示,Repo值为installed则表示已经安装;主要观察mysql-devel关键字的包是否已安装;如未安装,则输入yum install mysql-devel命令安装
依次安装mysql-devel、python-devel、python-setuptools,安装过程不报错则继续;
以上依赖项安装完成后,回到MySQL-python解压出的MySQL-python-1.2.3c1/目录;
>> python setup.py build
>> python setup.py install
以上两项命令正确执行,则表示python配置mysqldb成功,再次验证导入MySQLdb是否报错

如上表示配置MySQLdb成功
常见错误:python setup.py build提示找不到mysql_config
这个问题是因为在构建mysqldb时,使用MySQL-python-1.2.3c1/目录下的site.cfg文件中配置的mysql_config;

如果mysql的安装位置与site.cfg中配置的位置不符,则需要修改site.cfg文件的#mysql_config配置,取消前面的注释,并配置为正确的地址。例如
mysql_config = /usr/bin/mysql_config #(未指定的情形下,mysql_config的位置默认在/usr/bin目录,不同系统存在差异,具体可通过搜索文件获取实际位置)
验证python-Mysql功能
根据需要配置Mysql数据库,并修改好用户名与密码;
查看python-mysql基础语法,链接mysql数据库的mysql库,获取user表信息,代码如下;

执行结果如下:
[root@localhost python]# python mysql-conn.py
the user table content is: ('%', 'root', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', '', '', '', '', 0L, 0L, 0L, 0L, <br>'mysql_native_password', '123456', 'Y', datetime.datetime(2017, 9, 14, 14, 40, 2), None, 'N')
[root@localhost python]#
至此,Python配置Mysql验证通过!