python - 使用 PyMysql 将 python 代码与 Mysql 连接时出错
问题描述
亲爱的,我正在努力将 python 代码与 MysqlDB 连接......但是当我运行下面的代码时出现错误
import cursor as cursor
import pymysql.cursors
# Connect to the database
con = pymysql.connect(host='127.0.0.1', user='root', password='123', db='db', port=3306)
request = ('name', 'authorname', 'price', 'file', 'bookcover', 'description')
sql = ("INSERT INTO test"
"(Bookname,Author,price,file,Bookcover,about)"
"VALUES (%s, %s,%s, %s,%s, %s)")
cursor.execute(sql, request)
con.commit()
cursor.close()
con.close()
print('success')
/Users/sarahraad/PycharmProjects/untitled2/venv/bin/python /Users/sarahraad/PycharmProjects/untitled2/test1.py
Traceback (most recent call last):
File "/Users/sarahraad/PycharmProjects/untitled2/test1.py", line 5, in <module>
con = pymysql.connect(host='127.0.0.1', user='root', password='123', db='db', port=3306)
File "/Users/sarahraad/PycharmProjects/untitled2/venv/lib/python3.8/site-packages/pymysql/__init__.py", line 94, in Connect
return Connection(*args, **kwargs)
File "/Users/sarahraad/PycharmProjects/untitled2/venv/lib/python3.8/site-packages/pymysql/connections.py", line 325, in __init__
self.connect()
File "/Users/sarahraad/PycharmProjects/untitled2/venv/lib/python3.8/site-packages/pymysql/connections.py", line 599, in connect
self._request_authentication()
File "/Users/sarahraad/PycharmProjects/untitled2/venv/lib/python3.8/site-packages/pymysql/connections.py", line 882, in _request_authentication
auth_packet = _auth.caching_sha2_password_auth(self, auth_packet)
File "/Users/sarahraad/PycharmProjects/untitled2/venv/lib/python3.8/site-packages/pymysql/_auth.py", line 238, in caching_sha2_password_auth
pkt = conn._read_packet()
File "/Users/sarahraad/PycharmProjects/untitled2/venv/lib/python3.8/site-packages/pymysql/connections.py", line 684, in _read_packet
packet.check_error()
File "/Users/sarahraad/PycharmProjects/untitled2/venv/lib/python3.8/site-packages/pymysql/protocol.py", line 220, in check_error
err.raise_mysql_exception(self._data)
File "/Users/sarahraad/PycharmProjects/untitled2/venv/lib/python3.8/site-packages/pymysql/err.py", line 109, in raise_mysql_exception
raise errorclass(errno, errval)
pymysql.err.InternalError: (1049, "Unknown database 'db'")
Process finished with exit code 1
请你的建议
解决方案
错误在这一行:
con = pymysql.connect(host='127.0.0.1', user='root', password='123', db='db', port=3306)
确保说明您的实际数据库名称,而不仅仅是“db”。
例子:
con = pymysql.connect(host='127.0.0.1', user='root', password='123', db='name_of_db', port=3306)`