Issue
I'm using pymysql with Python 3.8 to allow Python to make connections to another MySQL server. I get an error:
with pymysql.connect('127.0.0.1', user = '123', password = '123', port = server.local_bind_port) as connection:
AttributeError: __enter__
python:
from sshtunnel import SSHTunnelForwarder
import pymysql
with SSHTunnelForwarder(
('76.21.187.192', 2222),
ssh_username = '123',
ssh_password = '123',
remote_bind_address = ('127.0.0.1', 3306)) as server:
with pymysql.connect('127.0.0.1', user = '123', password = '123', port = server.local_bind_port) as connection:
print('OK')
How to properly connect to MySQL?
Solution
When you use a with block in python, the object in the with statement gets its enter method called, the block inside the with runs, and then the exit gets called (optionally with exception info if one was raised). Thus, if you don't have an enter defined on your class, you'll see this error.
or else instead of above statement you use :
connection = pymysql.connect('127.0.0.1', user = '123', password = '123', port = server.local_bind_port)
Answered By - Kasim Sharif