Python连接MySQL- pymysql.err.InternalError: (1698, "Access denied for user 'root'@'localhost'")

本文介绍了一种常见的Python连接MySQL错误:pymysql.err.InternalError:(1698,Access denied for user 'root'@'localhost')。详细解释了在Ubuntu环境下安装MySQL时未设置密码导致的问题,并提供了设置MySQL密码的解决方案。

环境:

Python 3.6 + MySQL5.7 + ubuntu18.04

最近在学习 Python 连接 MySQL 时,出现了一个错误 pymysql.err.InternalError: (1698, "Access denied for user 'root'@'localhost'")。

由于刚接触这部分内容,不知道如何解决,逛了一些技术博客之后依旧未解决,但最后还是发现问题出在了MySQL上。

原因在于:在我的ubuntu中安装MySQL时,默认是没有设置密码的。用Python脚本连接MySQL时,MySQL拒绝访问。

解决办法:给MySQL设置密码!

设置密码的办法有很多,大家可以去博客上找,例如:https://blog.youkuaiyun.com/qq_38737992/article/details/81090373

设置完密码之后,再重新运行Python脚本,就可以连接上MySQL了!

--------------------------------------------------------------------------- OperationalError Traceback (most recent call last) <ipython-input-2-bb1780f10cf3> in <module> 27 28 # 连接 MySQL 数据库 ---> 29 conn = pymysql.connect( 30 host=&#39;localhost&#39;, 31 user=&#39;root&#39;, D:\Program Files\Anaconda3\lib\site-packages\pymysql\connections.py in __init__(self, user, password, host, database, unix_socket, port, charset, collation, sql_mode, read_default_file, conv, use_unicode, client_flag, cursorclass, init_command, connect_timeout, read_default_group, autocommit, local_infile, max_allowed_packet, defer_connect, auth_plugin_map, read_timeout, write_timeout, bind_address, binary_prefix, program_name, server_public_key, ssl, ssl_ca, ssl_cert, ssl_disabled, ssl_key, ssl_key_password, ssl_verify_cert, ssl_verify_identity, compress, named_pipe, passwd, db) 363 self._sock = None 364 else: --> 365 self.connect() 366 367 def __enter__(self): D:\Program Files\Anaconda3\lib\site-packages\pymysql\connections.py in connect(self, sock) 679 680 self._get_server_information() --> 681 self._request_authentication() 682 683 # Send "SET NAMES" query on init for: D:\Program Files\Anaconda3\lib\site-packages\pymysql\connections.py in _request_authentication(self) 956 957 self.write_packet(data) --> 958 auth_packet = self._read_packet() 959 960 # if authentication method isn&#39;t accepted the first byte D:\Program Files\Anaconda3\lib\site-packages\pymysql\connections.py in _read_packet(self, packet_type) 780 if self._result is not None and self._result.unbuffered_active is True: 781 self._result.unbuffered_active = False --> 782 packet.raise_for_error() 783 return packet 784 D:\Program Files\Anaconda3\lib\site-packages\pymysql\protocol.py in raise_for_error(self) 217 if DEBUG: 218 print("errno =", errno) --> 219 err.raise_mysql_exception(self._data) 220 221 def dump(self): D:\Program Files\Anaconda3\lib\site-packages\pymysql\err.py in raise_mysql_exception(data) 148 if errorclass is None: 149 errorclass = InternalError if errno < 1000 else OperationalError --> 150 raise errorclass(errno, errval) OperationalError: (1045, "Access denied for user &#39;root&#39;@&#39;localhost&#39; (using password: YES)")
最新发布
10-22
from flask import Flask, render_template, request, redirect, url_for, flash import pymysql from datetime import datetime app = Flask(__name__) # 配置数据库连接 app.config[&#39;MYSQL_HOST&#39;] = &#39;localhost&#39; app.config[&#39;MYSQL_USER&#39;] = &#39;root&#39; app.config[&#39;MYSQL_PASSWORD&#39;] = &#39;1&#39; app.config[&#39;MYSQL_DB&#39;] = &#39;message_board&#39; app.config[&#39;MYSQL_CURSORCLASS&#39;] = &#39;DictCursor&#39; # 配置会话密钥 app.secret_key = &#39;your_secret_key&#39; # 首页 - 分页显示留言 @app.route(&#39;/&#39;) @app.route(&#39;/page/<int:page>&#39;) def index(page=1): # 每页显示的留言数量 per_page = 5 # 计算偏移量 offset = (page - 1) * per_page # 连接数据库 conn = pymysql.connect( host=app.config[&#39;MYSQL_HOST&#39;], user=app.config[&#39;MYSQL_USER&#39;], password=app.config[&#39;MYSQL_PASSWORD&#39;], database=app.config[&#39;MYSQL_DB&#39;], cursorclass=pymysql.cursors.DictCursor ) try: # 创建游标 cur = conn.cursor() # 获取总留言数 cur.execute("SELECT COUNT(*) as total FROM messages") total_data = cur.fetchone() total_messages = total_data[&#39;total&#39;] # 计算总页数 total_pages = (total_messages + per_page - 1) // per_page # 获取当前页的留言 cur.execute("SELECT * FROM messages ORDER BY created_at DESC LIMIT %s OFFSET %s", (per_page, offset)) messages = cur.fetchall() return render_template(&#39;index.html&#39;, messages=messages, page=page, total_pages=total_pages) finally: # 关闭游标和连接 cur.close() conn.close() # 添加留言 @app.route(&#39;/add&#39;, methods=[&#39;POST&#39;]) def add_message(): if request.method == &#39;POST&#39;: name = request.form[&#39;name&#39;] content = request.form[&#39;content&#39;] created_at = datetime.now() # 连接数据库 conn = pymysql.connect( host=app.config[&#39;MYSQL_HOST&#39;], user=app.config[&#39;MYSQL_USER&#39;], password=app.config[&#39;MYSQL_PASSWORD&#39;], database=app.config[&#39;MYSQL_DB&#39;], cursorclass=pymysql.cursors.DictCursor ) try: # 创建游标 cur = conn.cursor() cur.execute("INSERT INTO messages (name, content, created_at) VALUES (%s, %s, %s)", (name, content, created_at)) conn.commit() flash(&#39;留言添加成功!&#39;) return redirect(url_for(&#39;index&#39;)) finally: # 关闭游标和连接 cur.close() conn.close() # 修改留言 - 显示修改表单 @app.route(&#39;/edit/<int:id>&#39;) def edit_message(id): # 连接数据库 conn = pymysql.connect( host=app.config[&#39;MYSQL_HOST&#39;], user=app.config[&#39;MYSQL_USER&#39;], password=app.config[&#39;MYSQL_PASSWORD&#39;], database=app.config[&#39;MYSQL_DB&#39;], cursorclass=pymysql.cursors.DictCursor ) try: # 创建游标 cur = conn.cursor() cur.execute("SELECT * FROM messages WHERE id = %s", (id,)) message = cur.fetchone() return render_template(&#39;edit.html&#39;, message=message) finally: # 关闭游标和连接 cur.close() conn.close() # 修改留言 - 处理表单提交 @app.route(&#39;/update/<int:id>&#39;, methods=[&#39;POST&#39;]) def update_message(id): if request.method == &#39;POST&#39;: name = request.form[&#39;name&#39;] content = request.form[&#39;content&#39;] updated_at = datetime.now() # 连接数据库 conn = pymysql.connect( host=app.config[&#39;MYSQL_HOST&#39;], user=app.config[&#39;MYSQL_USER&#39;], password=app.config[&#39;MYSQL_PASSWORD&#39;], database=app.config[&#39;MYSQL_DB&#39;], cursorclass=pymysql.cursors.DictCursor ) try: # 创建游标 cur = conn.cursor() cur.execute("UPDATE messages SET name = %s, content = %s, updated_at = %s WHERE id = %s", (name, content, updated_at, id)) conn.commit() flash(&#39;留言修改成功!&#39;) return redirect(url_for(&#39;index&#39;)) finally: # 关闭游标和连接 cur.close() conn.close() # 删除留言 @app.route(&#39;/delete/<int:id>&#39;) def delete_message(id): # 连接数据库 conn = pymysql.connect( host=app.config[&#39;MYSQL_HOST&#39;], user=app.config[&#39;MYSQL_USER&#39;], password=app.config[&#39;MYSQL_PASSWORD&#39;], database=app.config[&#39;MYSQL_DB&#39;], cursorclass=pymysql.cursors.DictCursor ) try: # 创建游标 cur = conn.cursor() cur.execute("DELETE FROM messages WHERE id = %s", (id,)) conn.commit() flash(&#39;留言删除成功!&#39;) return redirect(url_for(&#39;index&#39;)) finally: # 关闭游标和连接 cur.close() conn.close() if __name__ == &#39;__main__&#39;: app.run(debug=True, use_reloader=False) 这个代码运行报错,帮我修改它
05-10
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值