在mac pycharm中输入
import mysql.connector mydb = mysql.connector.connect( host="localhost", # 数据库主机地址 user='db', # 数据库用户名 passwd="12345678" # 数据库密码 ) print(mydb)
执行后抱错, MySQL ERROR 1045 (28000): Access denied for user ‘db‘@‘localhost‘ (using password:yes)
看了网上很多解释,但最终自己发现自己的原因和他们不一样,是很无语的一个原因。我的数据库用名填错了,填了一个自己安装mysql某一步中使用的用户名和密码,而这个“数据库用户名”要在terminal中查看验证一下。步骤如下
在Mac OS X上查看MySQL用户名的方法如下:
-
打开终端,输入mysql -u root -p并回车,进入MySQL控制台。
-
输入您的MySQL root密码,并回车。
-
输入以下命令并回车:SELECT user, host FROM mysql.user;
-
您将看到一个包含所有MySQL用户名的表格,其中user列显示用户名,host列显示主机名。
我查到的结果如下
dongbos-MacBook-Pro:~ eastavesun$ mysql -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 10
Server version: 8.1.0 MySQL Community Server - GPL
Copyright (c) 2000, 2023, Oracle and/or its affiliates.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> SELECT user, host FROM mysql.user;
+------------------+-----------+
| user | host |
+------------------+-----------+
| mysql.infoschema | localhost |
| mysql.session | localhost |
| mysql.sys | localhost |
| root | localhost |
+------------------+-----------+
4 rows in set (0.01 sec)
把以下三个都填对了,就成功了
host="localhost", # 数据库主机地址 user='db', # 数据库用户名 passwd="12345678" # 数据库密码。