python操作数据库MySql,windows和ubuntu下安装MySQLdb库报错:EnvironmentError: mys...
source link: https://blog.popkx.com/python-operation-database-mysql-windows-and-ubuntu-install-mysqldb-library-error/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
python 的 MySQLdb 库非常方便操作 mysql。不过安装确实非常多问题,这里记录 windows 下和 ubuntu 下安装
MySQLdb
库的过程。
ubuntu 下安装 python 的 MYSQLdb 库
首先想到的是:
sudo pip install Mysql-python
结果报错 EnvironmentError: mysql_config not found
:
查阅资料,发现缺少
libmysqlclient-dev
,安装之sudo apt-get install libmysqlclient-dev
继续安装 MYSQLdb,发现继续报错:
...
_mysql.c:29:20: fatal error: Python.h: No such file or directory
#include "Python.h"
^
compilation terminated.
error: command 'x86_64-linux-gnu-gcc' failed with exit status 1
...
Python.h
是python开发包,可能系统没有安装此开发包,执行如下命令:
sudo dpkg -l | grep python-dev
发现的确没有 python 开发包,安装之。
sudo apt-get install python-dev
再执行安装 MYSQLdb 库,发现成功了。
windows 下安装 python 的 MYSQLdb 库
windows 下真的非常多坑。一开始也是尝试了直接使用 pip install 安装,结果却提示错误:
error: Microsoft Visual C++ 9.0 is required. Get it from http://aka.ms/vcpython
按照提示,下载安装 Microsoft Visual C++ 9.0,结果继续报错。于是放弃这种安装方式,直接使用 whl 安装包安装。流程如下:
1. 输入以下命令,打印出我的电脑支持的 .whl 文件版本
>>import pip;
>>print(pip.pep425tags.get_supported())
执行,输出:
[('cp27', 'cp27m', 'win32'), ('cp27', 'none', 'win32'), ('py2', 'none',
'win32'), ('cp27', 'none', 'any'), ('cp2', 'none', 'any'), ('py27', 'none',
'any'), ('py2', 'none', 'any'), ('py26', 'none', 'any'), ('py25', 'none',
'any'), ('py24', 'none', 'any'), ('py23', 'none', 'any'), ('py22', 'none',
'any'), ('py21', 'none', 'any'), ('py20', 'none', 'any')]
2. 从上述打印结果中挑出一个版本 .whl 文件并下载
发现 (‘cp27’, ‘none’, ‘win32’),这个版本,然后去 这里 下载。
MySQL_python-1.2.5-cp27-none-win32.whl
注意,文件名不能修改,这是 whl 文件的特性。
3. 进入下载的 .whl 文件所在目录,输入如下命令安装
pip install MySQL_python-1.2.5-cp27-none-win32.whl
发现成功了。
python 使用 MySQLdb 库操作 mysql 数据库实例
代码如下:
#encoding=utf8
import MySQLdb
# 连接数据库
db = MySQLdb.connect(host, user, password, database, charset="utf8")
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# 使用execute方法执行SQL语句
cursor.execute(sql)
# 提交到数据库执行
db.commit()
# 使用 fetchone() fetchall()方法获取数据
data = cursor.fetchall()
# 关闭数据库
db.close()
其中 sql 是一条数据库语句,如 sql = “select * from testTable;”
阅读更多: Python
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK