在CentOS上安装mysql-python

18 投票
5 回答
113575 浏览
提问于 2025-04-16 08:11

我正在尝试在centos 5.5上安装MySQL-python这个库。我运行了

sudo yum install MySQL-python

但是当我尝试:

import MySQLdb

时,我遇到了这个错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "MySQLdb/__init__.py", line 22, in ?
    raise ImportError("this is MySQLdb version %s, but _mysql is version %r" %
ImportError: this is MySQLdb version (1, 2, 3, 'final', 0), \ # added linebreak
but _mysql is version (1, 2, 1, 'final', 1)

有没有什么线索可以帮我解决这个问题?

5 个回答

11

我使用的是Python 2.7.5、MySQL 5.6 和 CentOS 7.1.1503

对我来说,使用以下命令可以成功:

# pip install mysql-python

注意这里的前提条件:

安装 Python 的 pip 工具:

# rpm -iUvh http://dl.fedoraproject.org/pub/epel/7/x86_64/e/epel-release-7-5.noarch.rpm

# yum -y update
Reboot the machine (if kernel is also updated)

# yum -y install python-pip

安装 Python 的开发包:

# yum install python-devel

安装 MySQL 的开发包:

# yum install mysql-devel
41

第一步 - 安装软件包

# yum install MySQL-python
Loaded plugins: auto-update-debuginfo, langpacks, presto, refresh-packagekit
Setting up Install Process
Resolving Dependencies
--> Running transaction check
---> Package MySQL-python.i686 0:1.2.3-3.fc15 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

================================================================================
 Package              Arch         Version                 Repository      Size
================================================================================
Installing:
 MySQL-python         i686         1.2.3-3.fc15            fedora          78 k

Transaction Summary
================================================================================
Install       1 Package(s)

Total download size: 78 k
Installed size: 220 k
Is this ok [y/N]: y
Downloading Packages:
Setting up and reading Presto delta metadata
Processing delta metadata
Package(s) data still to download: 78 k
MySQL-python-1.2.3-3.fc15.i686.rpm                       |  78 kB     00:00     
Running rpm_check_debug
Running Transaction Test
Transaction Test Succeeded
Running Transaction
  Installing : MySQL-python-1.2.3-3.fc15.i686                               1/1 

Installed:
  MySQL-python.i686 0:1.2.3-3.fc15                                              

Complete!

第二步 - 测试是否正常工作

import MySQLdb
db = MySQLdb.connect("localhost","myusername","mypassword","mydb" )
cursor = db.cursor()
cursor.execute("SELECT VERSION()")
data = cursor.fetchone()    
print "Database version : %s " % data    
db.close()

输出结果:

Database version : 5.5.20 
3

你可能没有通过yum安装MySQL吧?在软件库里的MySQLDB版本是和软件库里的MySQL版本绑定在一起的,也就是说它们的版本需要一致。

你有两个选择:

  1. 安装MySQL的RPM版本。
  2. 把MySQLDB编译成与你的MySQL版本匹配的版本。

撰写回答