我是 Python 3 的新手,仍在学习,但我需要帮助。脚本的第一部分是:
import mysql.connector #this 作为 .py 失败但在 shell 中工作
cnx = mysql.connector.connect(user='root', password='mypassword', host='my_ip_address', database'name_of_database') #这在 shell 中有效
cursor = cnx.cursor()
我已经在 Python shell 中逐行尝试了上述操作,效果很好:我可以导入连接器以连接到我的数据库并取回数据。但是,当我将脚本另存为 .py 时,import mysql
连接器不起作用。我确实设置了 Path 变量,当我安装 mySQL 连接器时,它会将相关文件放在我的 Python 安装路径\Lib\site-pacakges 文件夹中。
我收到以下错误:
>Traceback (most recent call last):
> File "<frozen importlib._bootstrap>", line 1518, in _find_and_load_unlocked
AttributeError: 'module' object has no attribute '__path__'
在处理上述异常的过程中,又发生了一个异常:
>Traceback (most recent call last):
> File "C:\Users\Paul\Desktop\scripts\mysql.py", line 2, in <module>
> import mysql.connector
> File "C:\Users\Paul\Desktop\scripts\mysql.py", line 2, in <module>
> import mysql.connector
>ImportError: No module named 'mysql.connector'; mysql is not a package
最佳答案
我和你有同样的问题,我在你问同样问题的另一个网站上找到了答案。我将答案粘贴在这里作为引用。
The above happens because your script is named 'mysql.py', which is actually the same name as the 'mysql' package. Python correctly reports ImportError. Simply rename your 'mysql.py' to something else, like 'mysqlhacks.py'.
关于Python 3 mySQL.connector 卡住导入库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16055274/