工具:python3.6+mysql8.0+pymysqlpython
注意:python2.7之後的版本再也不支持 MySQLdb這個模塊。須要用pymysql,在命令行下安裝的方法 輸入pip install pymysql。mysql
import pymysql
conn = pymysql.Connect(
host='127.0.0.1',
port=3306,
user='root',
passwd='root',
db='imooc',
charset='utf8'
)
cursor = conn.cursor()
sql = 'select * from students'
# print(cursor)
cursor.execute(sql)
print(cursor.fetchall())
cursor.close()
conn.close()
執行這段代碼出錯 : pymysql.err.OperationalError: (1045, u"Access denied for user 'root'@'localhost' (using password: No)")
新版mysql使用的caching_sha2_password認證方式,換成mysql_native_password就能夠。sql
步驟是在cmd命令行鏈接mysql, python2.7
而後輸入ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'root';工具