我是Python 3的新手,仍然在学习,但我需要帮助.该脚本的第一部分是:
import mysql.connector #this is failing as a .py but works in the shell
cnx = mysql.connector.connect(user='root', password='mypassword', host='my_ip_address', database'name_of_database') #this works in the 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__'
Run Code Online (Sandbox Code Playgroud)
在处理上述异常期间,发生了另一个异常:
>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
Run Code Online (Sandbox Code Playgroud)
我和你有同样的问题,我在另一个网站上找到了答案,你问了同样的问题.我在这里粘贴答案作为参考.
之所以发生这种情况是因为您的脚本名为'mysql.py',它实际上与'mysql'包的名称相同.Python正确报告ImportError.只需将'mysql.py'重命名为其他内容,例如'mysqlhacks.py'.
取自https://answers.launchpad.net/myconnpy/+question/226992