I'm trying to connect to two MySQL databases (one local, one remote) at the same time using Python 3.4 but I'm really struggling. Splitting the problem into three:
Step 1: connect to the local DB. This is working fine
using PyMySQL. (MySQLdb isn't compatible with Python 3.4, of
course.)
Step 2: connect to the remote DB (which needs to
use SSH). I can get it to work from the Linux command prompt but not
from Python... see below.
Step 3: connect to both at the
same time. I think I'm supposed to use a different port for the
remote database so that I can have both connections at the same time
but I'm out of my depth here! If it's relevant then the two DBs will
have different names. And if this question isn't directly related,
please tell me and I'll post it separately.
Unfortunately I'm not really starting in the right place for a newbie... once I can get this working I can happily go back to basic Python and SQL but hopefully someone will take pity on me and give me a hand to get started!
For Step 2, my code is below. It seems to be quite close to the sshtunnel example which answers this question Python - SSH Tunnel Setup and MySQL DB Access - though that uses MySQLdb. For the moment I'm embedding the connection parameters – I'll move them to the config file once it's working properly.
import dropbox, pymysql, shlex, shutil, subprocess
from sshtunnel import SSHTunnelForwarder
import iot_config as cfg
def CloseLocalDB():
localcur.close()
localdb.close()
def CloseRemoteDB():
# Disconnect from the database
# remotecur.close()
# remotedb.close()
# Close the SSH tunnel
# ssh.close()
print("end of CloseRemoteDB function")
def OpenLocalDB():
global localcur, localdb
localdb = pymysql.connect(host=cfg.localdbconn['host'], user=cfg.localdbconn['user'], passwd=cfg.localdbconn['passwd'], db=cfg.localdbconn['db'])
localcur = localdb.cursor()
def OpenRemoteDB():
global remotecur, remotedb
with SSHTunnelForwarder(
('my_remote_site', 22),
ssh_username = "my_ssh_username",
ssh_private_key = "/etc/ssh/my_private_key.ppk",
ssh_private_key_password = "my_private_key_password",
remote_bind_address = ('127.0.0.1', 3308)) as server:
remotedb = None
#Following line gives an error if uncommented
# remotedb = pymysql.connect(host='127.0.0.1', user='remote_db_user', passwd='remote_db_password', db='remote_db_name', port=server.local_bind_port)
#remotecur = remotedb.cursor()
# Main program starts here
OpenLocalDB()
CloseLocalDB()
OpenRemoteDB()
CloseRemoteDB()
This is the error I'm getting:
2016-04-21 19:13:33,487 | ERROR | Secsh channel 0 open FAILED: Connection refused: Connect failed
2016-04-21 19:13:33,553 | ERROR | In #1 <-- ('127.0.0.1', 60591) to ('127.0.0.1', 3308) failed: ChannelException(2, 'Connect failed')
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 60591)
Traceback (most recent call last):
File "/usr/local/lib/python3.4/dist-packages/sshtunnel.py", line 286, in handle
src_address)
File "/usr/local/lib/python3.4/dist-packages/paramiko/transport.py", line 834, in open_channel
raise e
paramiko.ssh_exception.ChannelException: (2, 'Connect failed')
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/lib/python3.4/socketserver.py", line 613, in process_request_thread
self.finish_request(request, client_address)
File "/usr/lib/python3.4/socketserver.py", line 344, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "/usr/lib/python3.4/socketserver.py", line 669, in __init__
self.handle()
File "/usr/local/lib/python3.4/dist-packages/sshtunnel.py", line 296, in handle
raise HandlerSSHTunnelForwarderError(msg)
sshtunnel.HandlerSSHTunnelForwarderError: In #1 <-- ('127.0.0.1', 60591) to ('127.0.0.1', 3308) failed: ChannelException(2, 'Connect failed')
----------------------------------------
Traceback (most recent call last):
File "/home/pi/Documents/iot_pm2/iot_ssh_example_for_help.py", line 38, in <module>
OpenRemoteDB()
File "/home/pi/Documents/iot_pm2/iot_ssh_example_for_help.py", line 32, in OpenRemoteDB
remotedb = pymysql.connect(host='127.0.0.1', user='remote_db_user', passwd='remote_db_password', db='remote_db_name', port=server.local_bind_port)
File "/usr/local/lib/python3.4/dist-packages/pymysql/__init__.py", line 88, in Connect
return Connection(*args, **kwargs)
File "/usr/local/lib/python3.4/dist-packages/pymysql/connections.py", line 678, in __init__
self.connect()
File "/usr/local/lib/python3.4/dist-packages/pymysql/connections.py", line 889, in connect
self._get_server_information()
File "/usr/local/lib/python3.4/dist-packages/pymysql/connections.py", line 1190, in _get_server_information
packet = self._read_packet()
File "/usr/local/lib/python3.4/dist-packages/pymysql/connections.py", line 945, in _read_packet
packet_header = self._read_bytes(4)
File "/usr/local/lib/python3.4/dist-packages/pymysql/connections.py", line 981, in _read_bytes
2013, "Lost connection to MySQL server during query")
pymysql.err.OperationalError: (2013, 'Lost connection to MySQL server during query')
Thanks in advance.
Answering my own question because, with a lot of help from J.M. Fernández on Github, I have a solution: the example that I copied at the beginning uses port 3308 but port 3306 is the standard. Once I'd changed this it started working.
Related
I'm trying to establish a connection to MySQL server from IDLE and I can't figure out why I'm getting an error.
>>> dbconfig = {'host': '127.0.0.1',
'user': 'vsearch',
'password': 'vsearchpasswd',
'database': 'vsearchlogDB'}
>>> import mysql.connector
>>> conn = mysql.connector.connect(**dbconfig)
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
conn = mysql.connector.connect(**dbconfig)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/mysql/connector/__init__.py", line 179, in connect
return MySQLConnection(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/mysql/connector/connection.py", line 95, in __init__
self.connect(**kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/mysql/connector/abstracts.py", line 719, in connect
self._open_connection()
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/mysql/connector/connection.py", line 208, in _open_connection
self._do_auth(self._user, self._password,
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/mysql/connector/connection.py", line 137, in _do_auth
packet = self._protocol.make_auth(
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/mysql/connector/protocol.py", line 99, in make_auth
packet += self._auth_response(client_flags, username, password,
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/mysql/connector/protocol.py", line 58, in _auth_response
auth = get_auth_plugin(auth_plugin)(
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/mysql/connector/authentication.py", line 190, in get_auth_plugin
raise errors.NotSupportedError(
mysql.connector.errors.NotSupportedError: Authentication plugin 'caching_sha2_password' is not supported
I've tried these suggestions I found on stackoverflow :
shutting down mysql.server, installing mysql-connector-python and restarting mysql.server
passing an auth_plugin argument to the connect() method (as seen below)
auth_plugin='mysql_native_password'
made sure MySQL in listening to port 3306 (answer below)
localhost:mysql (LISTEN)
Versions:
mysql Ver 8.0.32 for macos12.6 on x86_64 (Homebrew)
Python 3.9.1
MacOS 12
Managed to fix issue by uninstalling MySQL connector and reinstalling it. Had issues with permissions so make sure you have permissions to read and write in connector directories.
This tutorial might help if your trying to connect to MySQL with MySQL-connector-python :
https://pynative.com/python-mysql-database-connection/
I m trying to connect to a mysql database. if server is not responding, my application crashes. I am using try, except but looks like two exceptions are raising and "try: except" could not handle it. can some one figure it out where is the problem. below is my code:-
def check_server(server_address):
con = mysql.connector.connect(host='{}'.format(server_address),
database='domicile_reports',
user='xyz',
password='xyz')
try:
if con.is_connected():
print('{} Connected'.format(server_address))
con.close()
except Exception as e:
print("Can not connect to db. {} Occured".format(e))
check_server('25.13.253.67')
Error displayed on terminal:-
Traceback (most recent call last):
File "C:\Users\Hamid Shah\AppData\Roaming\Python\Python310\site-packages\mysql\connector
network.py", line 574, in open_connection
self.sock.connect(sockaddr)
TimeoutError: [WinError 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
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "f:\Docs\OneDrive\Python Projects\CFC App\splash_screen_gui.py", line 151, in
obj = splashscreen()
File "f:\Docs\OneDrive\Python Projects\CFC App\splash_screen_gui.py", line 51, in init
self.check_server(self.server_2)
File "f:\Docs\OneDrive\Python Projects\CFC App\splash_screen_gui.py", line 80, in check_server
con = mysql.connector.connect(host='{}'.format(server_address),
File "C:\Users\Hamid Shah\AppData\Roaming\Python\Python310\site-packages\mysql\connector_init_.py", line 273, in connect
return MySQLConnection(*args, **kwargs)
File "C:\Users\Hamid Shah\AppData\Roaming\Python\Python310\site-packages\mysql\connector\connection.py", line 116, in init
self.connect(**kwargs)
File "C:\Users\Hamid Shah\AppData\Roaming\Python\Python310\site-packages\mysql\connector\abstracts.py", line 1052, in connect
self._open_connection()
File "C:\Users\Hamid Shah\AppData\Roaming\Python\Python310\site-packages\mysql\connector\connection.py", line 494, in _open_connection
self._socket.open_connection()
File "C:\Users\Hamid Shah\AppData\Roaming\Python\Python310\site-packages\mysql\connector\network.py", line 576, in open_connection
raise errors.InterfaceError(
mysql.connector.errors.InterfaceError: 2003: Can't connect to MySQL server on '25.13.253.67: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)
You need to put the connect() call inside the try: except block. You can also use a context manager to properly close the connection, example:
import mysql.connector
from mysql.connector.errors import Error
def check_server(server_address):
try:
with mysql.connector.connect(
host=server_address,
database="domicile_reports",
user="xyz",
password="xyz",
) as cnx:
print(f"{server_address} Connected")
except Error as err:
print(f"Can not connect to db. {err} Occured")
check_server("25.13.253.67")
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())
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
I have a mysql server on my computer. I did port fowarding on my modem. I checked port is open or not with signal sites and return success answer. When i try connect on my pc with host = "localhost" i returned success answer. But when i try connect mysql server with python.org's shell, i returned connection error same like this:
Traceback (most recent call last):
File “/usr/lib/python3.8/site-packages/mysql/connector/network.py”, line 529, 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 “”, line 1, in
File “/usr/lib/python3.8/site-packages/mysql/connector/init.py”, line 177, in connect
return MySQLConnection(*args, **kwargs)
File “/usr/lib/python3.8/site-packages/mysql/connector/connection.py”, line 104, in init
self.connect(**kwargs)
File “/usr/lib/python3.8/site-packages/mysql/connector/abstracts.py”, line 781, in connect
self._open_connection()
File “/usr/lib/python3.8/site-packages/mysql/connector/connection.py”, line 284, in _open_connection
self._socket.open_connection()
File “/usr/lib/python3.8/site-packages/mysql/connector/network.py”, line 531, in open_connection
raise errors.InterfaceError(
mysql.connector.errors.InterfaceError: 2003: Can’t connect to MySQL server on ‘myipadress:3306’ (111 Con
nection refused)
How can i connect my mysql server ?
In order to encounter this error first do the following:
Make sure the host is in the format 127.0.0.1 and there are no / or \ in the host name
Check if you have specified all the correct info about the server like passwords, user, root, etc
Make sure the server is active and there is no fire wall blocking your access
Remove all the unwanted users from the server