背景:

在python中默认没有安装MySQLdb,所以导入时会报错"No module named MySQLdb",

解决办法:

第1步 下载MySQL-python-1.2.5

32位下载地址:MySQL-python-1.2.5
打开后如下图,直接下载exe文件即可。

64位下载地址:
http://download.csdn.net/download/jxl1994/9989628

我把exe文件夹放在了python的安装目录下:

D:\python2.7\MySQL-python-1.2.5.win-amd64-py2.7.exe

第2步 运行MySQL-python-1.2.5.exe

直接双击,根据提示点击下一步安装即可。
有可能会出现“python2.7 not found”类似的错误提示,解决方法:
新建一个reg.py的文件,贴入下列代码并保存:

#
# script to register Python 2.0 or later for use with win32all
# and other extensions that require Python registry settings
#
# written by Joakim Loew for Secret Labs AB / PythonWare
#
# source:
# http://www.pythonware.com/products/works/articles/regpy20.htm
#
# modified by Valentine Gogichashvili as described in http://www.mail-archive.com/distutils-sig@python.org/msg10512.html
 
import sys
 
from _winreg import *
 
# tweak as necessary
version = sys.version[:3]
installpath = sys.prefix
 
regpath = "SOFTWARE\\Python\\Pythoncore\\%s\\" % (version)
installkey = "InstallPath"
pythonkey = "PythonPath"
pythonpath = "%s;%s\\Lib\\;%s\\DLLs\\" % (
installpath, installpath, installpath
)
 
def RegisterPy():
try:
reg = OpenKey(HKEY_CURRENT_USER, regpath)
except EnvironmentError as e:
try:
reg = CreateKey(HKEY_CURRENT_USER, regpath)
SetValue(reg, installkey, REG_SZ, installpath)
SetValue(reg, pythonkey, REG_SZ, pythonpath)
CloseKey(reg)
except:
print "*** Unable to register!"
return
print "--- Python", version, "is now registered!"
return
if (QueryValue(reg, installkey) == installpath and
QueryValue(reg, pythonkey) == pythonpath):
CloseKey(reg)
print "=== Python", version, "is already registered!"
return
CloseKey(reg)
print "*** Unable to register!"
print "*** You probably have another Python installation!"
 
if __name__ == "__main__":
RegisterPy()  

运行 reg.py ,输出"— Python 2.7 is now registered!" 说明已成功解决

第3步 运行Python Shell,导入MySQLdb

在python shell中输入import MySQldb,没有报错说明安装成功

附加说明

1、在下载Mysql-python-1.2.5时,也可以下载zip文件,下载后解压。在命令行下输入以下两行命令:
python setup.py build
python setup.py install

如果报错“Microsoft Visual C++ 9.0 is required”:

error: Microsoft Visual C++ 9.0 is required. Get it from http://aka.ms/vcpython27

这是因为电脑没有C++的编译环境,只要下载安装适用于Python2.7的VC++ Compiler就可以解决啦
Microsoft Visual C++ Compiler for Python 2.7

2、import MySQLdb的时候报错“DLL load failed: %1 不是有效的 Win32 应用程序
解决方法:这是因为你用64位的系统访问32的应用程序导致的,只要重新下载64位的MySQL-python即可。
64位下载地址:
http://download.csdn.net/download/jxl1994/9989628

Logo

更多推荐