【发布时间】:2025-12-19 05:55:12
【问题描述】:
对于 Python 和 SQL 来说都是新手,所以请原谅我的笨拙。我们在我的公司有一台服务器,我正试图通过一些 python 代码连接它。我有正确的 IP 地址和登录凭据,我可以在 SQL Server Management Studio 中毫无问题地连接到它,但我无法通过 PyCharm 的数据库功能或我的代码连接到它。如果有什么不同,我正在运行 python 3.6。
这是我正在运行的代码(为了安全起见,我省略了服务器 IP 地址和登录凭据):
import pymysql
db = pymysql.connect(host='server ip',
port=1433,
user='username',
passwd='password',
db='Development DB')
cursor = db.cursor()
cursor.execute("SELECT VERSION()")
data = cursor.fetchone()
print("Database version : %s" % data)
db.close()
当我运行代码时,大约 2 分钟没有发生任何事情后,我收到此错误:
Traceback (most recent call last):
File "C:\Program Files\Python35\lib\site-packages\pymysql\connections.py", line 1021, in _read_bytes
data = self._rfile.read(num_bytes)
File "C:\Program Files\Python35\lib\socket.py", line 575, in readinto
return self._sock.recv_into(b)
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:/Users/aubrey_s/PycharmProjects/Drawings_Converter/Drawings_Converter.py", line 5, in <module>
db = pymysql.connect(host='ip address', port=1433, user='username', passwd='password', db='Development DB')
File "C:\Program Files\Python35\lib\site-packages\pymysql\__init__.py", line 90, in Connect
return Connection(*args, **kwargs)
File "C:\Program Files\Python35\lib\site-packages\pymysql\connections.py", line 706, in __init__
self.connect()
File "C:\Program Files\Python35\lib\site-packages\pymysql\connections.py", line 931, in connect
self._get_server_information()
File "C:\Program Files\Python35\lib\site-packages\pymysql\connections.py", line 1245, in _get_server_information
packet = self._read_packet()
File "C:\Program Files\Python35\lib\site-packages\pymysql\connections.py", line 987, in _read_packet
packet_header = self._read_bytes(4)
File "C:\Program Files\Python35\lib\site-packages\pymysql\connections.py", line 1029, in _read_bytes
"Lost connection to MySQL server during query (%s)" % (e,))
pymysql.err.OperationalError: (2013, 'Lost connection to MySQL server during query ([WinError 10054] An existing connection was forcibly closed by the remote host)')
据我了解,似乎建立了连接,但服务器强制它在一段时间后关闭。谁能让我更深入地了解问题可能是什么?提前致谢!
【问题讨论】:
-
删除了 sql server 标签,因为这显然是一个 mysql 问题。
-
你检查权限了吗
-
如何查看权限?我刚刚用Java写了一些类似的代码,它连接得很好。
标签: python mysql python-3.x pymysql