我是python的新手,我在mysql网站上使用python 3.6和mysql连接器
pip install --allow-external mysql-connector-python mysql-connector-python
一切都很顺利。我试过mysql网站的3个例子 创建数据库和表,插入,选择。
但是在第二个例子后它停止工作并发出错误
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='Jinqm21k',
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()
所有示例都停止工作,包括创建,插入,选择
我无法弄清楚它有什么问题
答案 0 :(得分:1)
您的问题是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()