Python3.5拒绝使用MySQL Conn

2024-04-19 04:03:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我在这里读到了一些问题,人们都有和我一样的情况,但无论我尝试了什么方法,都不会奏效!在

根据MySQL文档,MySQL-connector-python-2.x.x.x应该与python3+一起使用。我已经下载了RPM包并将其安装在我的virtualenv中。但是,在导入库时,我得到错误消息,“没有名为MySQL的模块”。在

正在检查是否已安装程序包:

^{1}$

正在尝试安装程序包:

^{pr2}$

这适用于Python2.6:

[centos ~]$ python
Python 2.6.6 (r266:84292, Jul 23 2015, 15:22:56) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-11)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import MySQLdb
>>> import mysql.connector
>>> 

5.5Python不会:

[centos ~]$ python3.5
Python 3.5.1 (default, Jan 13 2016, 17:43:34) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-11)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import mysql.connector
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named 'mysql'
>>> 

通过MySQL文档验证了包:

(virtual)[centos]$ python
Python 3.5.1 (default, Jan 13 2016, 17:43:34) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-11)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 
>>> from distutils.sysconfig import get_python_lib
>>> print (get_python_lib ())
/home/<username>/Documents/redhat-server/python_project/virtual/lib/python3.5/site-packages
>>> 
>>> import mysql.connector
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named 'mysql'
>>> 

确保python3.5与MySQL.connector在

(virtual)[centos]$ which python3.5
~/Documents/redhat-server/python_project/virtual/bin/python3.5

更新:

(virtual)[centos]$ pip install mysql-connector-python
Collecting mysql-connector-python
  Could not find a version that satisfies the requirement mysql-connector-python (from versions: )
No matching distribution found for mysql-connector-python
(virtual)[centos]$

我做错什么了?在


Tags: importforconnectoronhattypemysqlvirtual
1条回答
网友
1楼 · 发布于 2024-04-19 04:03:38

我已经想好了。Anzel说的没错,它是全局安装在默认python2.6目录中的。我是这样修复的:

启动默认的python解释器,在我的例子中是“python”->;python2.6,然后运行下面的命令查看MySQL.connector“已安装。在

>>> from distutils.sysconfig import get_python_lib
>>> print get_python_lib ()
/usr/lib/python2.6/site-packages
>>> 

导航到上面的目录,“/usr/lib/python2.6/site packages/”显示一个名为MySQL的目录和一个名为MySQL的文件MySQL_connector_python-2.1.3-py2.6.egg-info。在

启动python3.5解释器将我带到另一个路径,我检查了这个路径并确信,两个MySQL和MySQL_connector_python-2.1.3-py2.6.egg-info文件/目录不在那里。在

^{pr2}$

接下来,我将这两个文件复制到Python3.5站点包目录中,测试了导入、数据库连接,并且成功了!在

Python 3.5.1 (default, Jan 13 2016, 17:43:34) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-11)] on linux
Type "copyright", "credits" or "license()" for more information.
>>> 
>>> import mysql.connector
>>> 
>>> cnx = mysql.connector.connect (user = 'username', password = 'password', host = 'localhost',
               database = 'testdb')
>>> cnx
<mysql.connector.connection.MySQLConnection object at 0x7ffa4c1009b0>

相关问题 更多 >