attributeerror:模块“mysql”没有属性“connector”

lb3vh1jj  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(616)

我是python的新手,我在mysql网站上使用python3.6和mysql连接器

pip install --allow-external mysql-connector-python mysql-connector-python

一切都很顺利。我尝试了mysql网站的3个例子,创建db和table,insert,select。
但在第二个例子之后,它停止工作并给出一个错误

Traceback (most recent call last):
  File "select.py", line 3, in <module>
    import mysql.connector
  File "C:\Users\preet\AppData\Local\Programs\Python\Python36\lib\site-packages\
mysql\connector\__init__.py", line 37, in <module>
    from .connection import MySQLConnection
  File "C:\Users\preet\AppData\Local\Programs\Python\Python36\lib\site-packages\
mysql\connector\connection.py", line 45, in <module>
    from .network import MySQLUnixSocket, MySQLTCPSocket
  File "C:\Users\preet\AppData\Local\Programs\Python\Python36\lib\site-packages\
mysql\connector\network.py", line 28, in <module>
    import socket
  File "C:\Users\preet\AppData\Local\Programs\Python\Python36\lib\socket.py", li
ne 52, in <module>
    import os, sys, io, selectors
  File "C:\Users\preet\AppData\Local\Programs\Python\Python36\lib\selectors.py",
 line 11, in <module>
    import select
  File "C:\Users\preet\Desktop\ptyhon-newspaper\select.py", line 7, in <module>
    cnx = mysql.connector.connect(user='root', password='Jinqm21k',
AttributeError: module 'mysql' has no attribute 'connector'

示例代码

from __future__ import print_function
from datetime import date, datetime, timedelta
import mysql.connector

cnx = mysql.connector.connect(user='root', password='****',
                              host='localhost',
                              database='worpress')
cursor = cnx.cursor()                             

query = ("SELECT first_name, last_name, hire_date FROM employees "
         "WHERE hire_date BETWEEN %s AND %s")

hire_start = datetime.date(1999, 1, 1)
hire_end = datetime.date(1999, 12, 31)

cursor.execute(query, (hire_start, hire_end))

for (first_name, last_name, hire_date) in cursor:
  print("{}, {} was hired on {:%d %b %Y}".format(
    last_name, first_name, hire_date))

cursor.close()  
cnx.close()

所有示例都停止工作,包括create、insert和select
我想不出它有什么毛病

bxpogfeg

bxpogfeg1#

您的问题是mysql库试图导入一些导入“select”包的包,这些包被您的模块“select.py”隐藏。请在重命名“select.py”后对现在不起作用的内容进行更新回溯。
我还建议您不要在.py文件本身中编写代码,除非您希望在模块导入时执行此代码。创建一个例程并在 __main__ 部分。

from __future__ import print_function
from datetime import date, datetime, timedelta
import mysql.connector

def print_employees():
    cnx = mysql.connector.connect(user='root', password='Jinqm21k',
                              host='localhost',
                              database='worpress')
    cursor = cnx.cursor()
    ...

if __name__ = '__main__':
    print_employees()

相关问题