Trouble establishing connection to server with PyMySQL [WinError 10054] - python

Pretty new to both Python and SQL, so please excuse my noobishness. We have a server at my company that I'm trying to connect to through some python code. I have the correct IP address and logon credentials, and I can connect to it in SQL Server Management Studio without any issues, but I can't connect to it through PyCharm's database feature or through my code. I'm running python 3.6 if that makes a difference.
This is the code that I'm running (I've omitted the server ip address and logon credentials for security):
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()
When I run the code, after about 2 minutes of nothing happening I get this error:
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)')
From what I can understand, it looks like a connection was established, but the server forced it to close after a while. Can anyone offer me some more insight into what the problem might be? Thanks in advance!

As I wrote in another post, you may want to try using pymssql, in case your database is not a MySQL DB but a Microsoft SQL DB.

Related

Can't connect Python program to remote MySQL database over the same network

Can someone please help me? I am trying to make a simple python - MySQL connection. the code is running on my Dell-Windows Laptop, while the server is running on my Acer-Linux Laptop, they are connected on the same network. But upon running the query it prompts me with this error : Firewall is disabled for both. I tried pinging both of them vise versa and is working. In fact, I have a program with LibreOffice Base and they are interacting properly. But when I try to translate just a simple query in PYTHON seems like it is not working, I just don't know what could be the error on my code. Thank you so much for you help.
Traceback (most recent call last):
File "C:\Users\JM Dela Cruz\Documents\pyproj\myproject\test1.py", line 3, in <module>
mydb = mysql.connector.connect(
File "C:\Users\JM Dela Cruz\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\mysql\connector\pooling.py", line 287, in connect
return MySQLConnection(*args, **kwargs)
File "C:\Users\JM Dela Cruz\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\mysql\connector\connection.py", line 137, in __init__
self.connect(**kwargs)
File "C:\Users\JM Dela Cruz\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\mysql\connector\abstracts.py", line 1095, in connect
self._open_connection()
File "C:\Users\JM Dela Cruz\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\mysql\connector\connection.py", line 533, in _open_connection
self._socket.open_connection()
File "C:\Users\JM Dela Cruz\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\mysql\connector\network.py", line 569, in open_connection
raise InterfaceError(
mysql.connector.errors.InterfaceError: 2003: Can't connect to MySQL server on '198.168.101.42:3306' (10060 A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond)
My Python Code :
import mysql.connector
mydb = mysql.connector.connect(
host="198.168.101.42",
user="vsearch",
password="vsearchpasswd",
database="classicmodels",
port="3306"
)
mycursor = mydb.cursor()
_SQL="Select * From employees"
myresult = mycursor.execute(_SQL)
print(myresult.fetchall())

can't remotely connect to mysql database in cpanel with python

I tried to connect remotely to my database in cpanel in all ways but it won't let me, does anyone know why it doesn't give me access?
HOST = "xxxxxxxxx"
DATABASE = "xxxxxxxxx"
USER = "xxxxxxxxxxx"
PASSWORD = "xxxxxxx"
db_connection = mysql.connect(host=HOST, database=DATABASE, user=USER, password=PASSWORD)
print("Connected to:", db_connection.get_server_info())
#####################################################################################
python3 sqlConect.py
Traceback (most recent call last):
File "/home/miguel/.local/lib/python3.10/site-packages/mysql/connector/network.py", line 509, in open_connection
self.sock.connect(sockaddr)
ConnectionRefusedError: [Errno 111] Connection refused
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/miguel/Desktop/python/sqlConect.py", line 61, in <module>
db_connection = mysql.connect(host=HOST, database=DATABASE, user=USER, password=PASSWORD)
File "/home/miguel/.local/lib/python3.10/site-packages/mysql/connector/__init__.py", line 179, in connect
return MySQLConnection(*args, **kwargs)
File "/home/miguel/.local/lib/python3.10/site-packages/mysql/connector/connection.py", line 95, in __init__
self.connect(**kwargs)
File "/home/miguel/.local/lib/python3.10/site-packages/mysql/connector/abstracts.py", line 716, in connect
self._open_connection()
File "/home/miguel/.local/lib/python3.10/site-packages/mysql/connector/connection.py", line 206, in _open_connection
self._socket.open_connection()
File "/home/miguel/.local/lib/python3.10/site-packages/mysql/connector/network.py", line 511, in open_connection
raise errors.InterfaceError(
mysql.connector.errors.InterfaceError: 2003: Can't connect to MySQL server on 'industriasbjt.com:3306' (111 Connection refused)
In cpanel when you try to connect remotely and access is denied by port 3306, you have to contact the cpanel provider and check the plans that give remote access, because if port 3306 is blocked the remote connection plan may is limited, it's just a matter of talking to the provider that provides the cpanel

Can't connect to MySQL server on 'localhost:3306' (10061) During handling of the above exception in python

i wrote a program to check if program can make connection to MySQL server and if cant connect to server print a error message and this is the program that i wrote
import mysql.connector
is_connected = False
def check_connection():
global is_connected
try:
db = mysql.connector.connect(
host="localhost",
user="root",
passwd=""
)
if db.is_connected():
print("Connected to MySQL database")
is_connected = True
except:
print("Unable to connect to MySQL database check if mysql server is running on defaul port which is 3306")
return is_connected
the whole objective here is print a error message when MySQL server is not running so i stop the server and run the file it works fine when in its own file but when it import to another file and call the check_cconnection method its give this error
Traceback (most recent call last):
File "C:\Users\thevi\AppData\Local\Programs\Python\Python310\lib\site-packages\mysql\connector\connection_cext.py", line 236, in _open_connection
self._cmysql.connect(**cnx_kwargs)
_mysql_connector.MySQLInterfaceError: Can't connect to MySQL server on 'localhost:3306' (10061)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "t:\Projects\Python_Projects\assignment\anatha.py", line 2, in <module>
from create_db import createDb
File "t:\Projects\Python_Projects\assignment\create_db.py", line 3, in <module>
db = mysql.connector.connect(
File "C:\Users\thevi\AppData\Local\Programs\Python\Python310\lib\site-packages\mysql\connector\__init__.py", line 272, in connect
return CMySQLConnection(*args, **kwargs)
File "C:\Users\thevi\AppData\Local\Programs\Python\Python310\lib\site-packages\mysql\connector\connection_cext.py", line 85, in __init__
self.connect(**kwargs)
File "C:\Users\thevi\AppData\Local\Programs\Python\Python310\lib\site-packages\mysql\connector\abstracts.py", line 1028, in connect
self._open_connection()
File "C:\Users\thevi\AppData\Local\Programs\Python\Python310\lib\site-packages\mysql\connector\connection_cext.py", line 241, in _open_connection
raise errors.get_mysql_exception(msg=exc.msg, errno=exc.errno,
mysql.connector.errors.DatabaseError: 2003 (HY000): Can't connect to MySQL server on 'localhost:3306' (10061)
how to ger rid of this error

PyMySQL:- OperationalError: (2003, "Can't connect to MySQL server on 'localhost' ([Errno 111] Connection refused)")

I am trying to run a scrapy spider and whenever the spider opens/scrapes/closes I am saving data to a pymysql database. When I was running on RDS it was not giving any kind of error, however when I switched to my localhost it is giving me a 'Connection refused error'.
Here's the code for my runner.py file
import pymysql
connection = pymysql.connect(
host='127.0.0.1',
port='3306',
user='root',
password='lifeisgood',
db='scrapy_dev'
)
# rest of code
and here's the complete stacktrace of the error:
Traceback (most recent call last):
File "/home/technophile/.local/lib/python3.8/site-packages/pymysql/connections.py", line 581, in connect
sock = socket.create_connection(
File "/usr/lib/python3.8/socket.py", line 808, in create_connection
raise err
File "/usr/lib/python3.8/socket.py", line 796, in create_connection
sock.connect(sa)
ConnectionRefusedError: [Errno 111] Connection refused
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "runner.py", line 23, in <module>
connection = pymysql.connect(
File "/home/technophile/.local/lib/python3.8/site-packages/pymysql/__init__.py", line 94, in Connect
return Connection(*args, **kwargs)
File "/home/technophile/.local/lib/python3.8/site-packages/pymysql/connections.py", line 325, in __init__
self.connect()
File "/home/technophile/.local/lib/python3.8/site-packages/pymysql/connections.py", line 630, in connect
raise exc
pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on 'localhost' ([Errno 111] Connection refused)")
I've tried ways by looking at other stackoverflow answers but none of them helped so far.
Please help me.
Take a closer look at the configuration. It must be a configuration problem. Please check the remote code is not synchronized!

Python mysql (using pymysql) failing to connect

I am using Python Pymysql to connect to AWS RDS db.
This was working all these days but now I am not able to connect to the db.
However when I am using the same machine and same credentials it does connect through Mysql workbench, but through pycharm this does not work.,
Code :
configParser = ConfigParser.RawConfigParser()
configFilePath = r'docs/credentials.cfg'
configParser.read(configFilePath)
User = configParser.get('aws-config','user')
Pswd = configParser.get('aws-config','pswd')
Host = configParser.get('aws-config','hostdps')
Databs = configParser.get('aws-config','databs')
db = pymysql.connect(host=Host, user=User, password=Pswd, db=Databs, charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor,local_infile=True)
Error :
File "/usr/local/lib/python2.7/dist-packages/pymysql/__init__.py", line 90, in Connect
return Connection(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/pymysql/connections.py", line 688, in __init__
self.connect()
File "/usr/local/lib/python2.7/dist-packages/pymysql/connections.py", line 906, in connect
self._request_authentication()
File "/usr/local/lib/python2.7/dist-packages/pymysql/connections.py", line 1114, in _request_authentication
auth_packet = self._read_packet()
File "/usr/local/lib/python2.7/dist-packages/pymysql/connections.py", line 961, in _read_packet
packet_header = self._read_bytes(4)
File "/usr/local/lib/python2.7/dist-packages/pymysql/connections.py", line 995, in _read_bytes
"Lost connection to MySQL server during query (%s)" % (e,))
pymysql.err.OperationalError: (2013, 'Lost connection to MySQL server during query ([Errno 104] Connection reset by peer)')
How to make sure that this does not happen on production? (prevent such failures in the future).
why u not use connection pool for these?
connection pool can auto manage connection,so can fix this.
U can try any python mysql pool .
pool example
for this this link
or directly use github handy code .PyMysqlPool

Categories