2006, 'SSL connection error: unknown error number' - mysql

I'm using Anaconda and python3.7 and I'm trying to connect to a remote database using the following code:
import MySQLdb
myDB = MySQLdb.connect(host="xxxxx", port=3306, user="xxx",password="xxxx",db="xxxx")
but I get the following error:
File "C:\Users\zanto\anaconda3\lib\site-packages\MySQLdb\connections.py", line 208, in __init__
super(Connection, self).__init__(*args, **kwargs2)
OperationalError: (2006, 'SSL connection error: unknown error number')
I tried 2 users in mysql one using % and one using localhost but I still get the same error.

It was a problem of mySQLdb library.
I installed pymysql library through anaconda and now it's working!
My new code is:
import pymysql.cursors
connection = pymysql.connect(host='xxxx',port=3306,user="xxxx",password="xxxx",db="xxxx", cursorclass=pymysql.cursors.DictCursor)
try:
with connection.cursor() as cursor:
sql="SELECT * FROM Table WHERE Field = 'value'"
cursor.execute(sql)
results = cursor.fetchall()
#print (results) #if you remove the comment you will get the query result as a dictionary
for record in results:
record_line = " ".join('{0}{1}'.format(field,value) for field,value in record.items())
print(record_line)
finally:
connection.close()
More info: A cursor allows Python code to execute MySQL command in a database session. A cursor is created by the connection.cursor() method: they are bound to the connection for the entire lifetime and all the commands are executed in the context of the
database session wrapped by the connection.
The cursor.execute() method runs a query in MySQL database. The cursor.fetchall() method returns the results of a query in list form that contains the records as dictionaries.

Related

Over time losing connection to mysql server during queries

I am running a discord bot using a MySQL server which are BOTH running on my UBUNTU 18.04 server. It works fine, but after a few hours I start to get an error any time I access the database.
Traceback (most recent call last):
File "/home/narnar/.local/lib/python3.7/site-packages/discord_slash/client.py", line 1352, in invoke_command
await func.invoke(ctx, **args)
File "/home/narnar/.local/lib/python3.7/site-packages/discord_slash/model.py", line 209, in invoke
return await self.func(self.cog, *args, **kwargs)
File "/home/narnar/cool-art/cogs/artlevels.py", line 120, in leaderboardCommand
cur.execute("SELECT * FROM artLevels")
File "/home/narnar/.local/lib/python3.7/site-packages/mysql/connector/cursor_cext.py", line 271, in execute
raw_as_string=self._raw_as_string)
File "/home/narnar/.local/lib/python3.7/site-packages/mysql/connector/connection_cext.py", line 522, in cmd_query
sqlstate=exc.sqlstate)
mysql.connector.errors.OperationalError: 2013 (HY000): Lost connection to MySQL server during query
I solved this issue by not having connections open for too long. My program connected to the MySQL server at the beginning of the program and used that same connection all the time. So instead of having one connection, I just opened a connection when I needed to access the database then closed it afterwards. Just make sure you don't have your connection open for too long
Don't do this:
con = mysql.connector.connect(
host=host,
user="ImNotThat",
passwd="Stupid",
database="toShowMyPasswords"
)
async def someListenerEvent():
doThing()
con.commit()
Do this:
async def someListenerEvent():
con = mysql.connector.connect(
host=host,
user="ImNotThat",
passwd="Stupid",
database="toShowMyPasswords"
)
doThing()
con.commit()
cur.close()
con.close()

Pythonanywhere giving MySQL connection error even without time delay

I am trying to connect to my pythonanywhere DB from a local python file, using the following code.
import MySQLdb, sshtunnel
sshtunnel.SSH_TIMEOUT = 5.0
sshtunnel.TUNNEL_TIMEOUT = 5.0
queryAdd = ("INSERT INTO `****$geo***`.O***"
"(name, address) "
"VALUES (%s, %s)")
with sshtunnel.SSHTunnelForwarder(
('ssh.pythonanywhere.com'),
ssh_username='*******', ssh_password='*******',
remote_bind_address=('*****.mysql.pythonanywhere-services.com', 3306)
) as tunnel:
connection = MySQLdb.connect(
user='******',
passwd='********',
host='127.0.0.1', port=tunnel.local_bind_port,
db='****$geo******',
)
cursor = connection.cursor()
for row in dl:
tup=(row['name'],row['address'])
cursor.execute(queryAdd, tup)
connection.commit()
However, as soon as the code is run, I get the following error:
MySQLdb._exceptions.OperationalError: (2013, 'Lost connection to MySQL server during query')
There is no delay between creating the connection and running the query. What am I doing wrong?
You need to do everything inside your with block as the tunnel is gone when you go outside of the context.

ModuleNotFoundError: No module named 'mysql.connector'; 'mysql' is not a package v2021

I'm trying a simple database connection.
"""
import mysql.connector
from mysql.connector import Error
try:
connection = mysql.connector.connect(host='localhost',
database='options',
user='root',
password='xxxxx')
if connection.is_connected():
db_Info = connection.get_server_info()
print("Connected to MySQL Server version ", db_Info)
cursor = connection.cursor()
cursor.execute("select database();")
record = cursor.fetchone()
print("You're connected to database: ", record)
except Error as e:
print("Error while connecting to MySQL", e)
finally:
if connection.is_connected():
cursor.close()
connection.close()
print("MySQL connection is closed")
"""
This works - once - if I uninstall and reinstall MySQL. When I try it a second time if fails to the above Traceback. When it works I've tried a simple read of some of the data. This also works only once per reinstall.
"""
import mysql.connector
try:
connection = mysql.connector.connect(host='localhost',
database='options',
user='root',
password=xxxxxx)
sql_select_Query = "SELECT command” (my SELECT command is lengthy so I’ve omitted it)
cursor = connection.cursor()
cursor.execute(sql_select_Query)
# get all records
records = cursor.fetchall()
print("Total number of rows in table: ", cursor.rowcount)
print("\nPrinting each row")
for row in records:
print("col1 = ", row[0], )
print("col2 = ", row[1])
print("col3 = ", row[2])
print("col4= ", row[3], "\n")
except mysql.connector.Error as e:
print("Error reading data from MySQL table", e)
finally:
if connection.is_connected():
connection.close()
cursor.close()
print("MySQL connection is closed")
"""
I've done the MySQL installation of the server, workbench, and connector (3x).
I'm using Windows 10 Home with the latest Anaconda release.
Python 3.8.11 (default, Aug 6 2021, 09:57:55) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
I’ve uninstalled ALL mysql entries in the pip list and reinstalled them (multiple times).
I have no issues accessing the database from MySQL Workbench.
(base) PS C:\Users\WARNE> pip list
Package Version
mysql 0.0.3
mysql-connector-python 8.0.26
mysqlclient 2.0.3
(base) PS C:\Users\WARNE> conda install -c anaconda mysql-connector-python
Collecting package metadata (current_repodata.json): done
Solving environment: failed with initial frozen solve. Retrying with flexible solve.
…this continued to fail
I've tried about every solution in all of the related questions without any luck. Any help/suggestions would be appreciated.
I finally went back to basics and re-installed, went to very simple code, etc. and this started working. This seems to be a weakness in python-MySQL interworking. This was frustrating.

Error when connecting to MySQL database using mysql.connector

I am trying to connect to a MySQL database using mysql.connector:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="user",
password="password",
database="database"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM table")
myresult = mycursor.fetchone()
print(myresult)
I get this error message:
errno=2003, values=(self.get_address(), _strioerror(err)))
mysql.connector.errors.InterfaceError: 2003: Can't connect to MySQL server on'localhost:3306'(10061 No connection could be made because the target machine actively refused it)
Does this mean that there something wrong with the database credentials?

Query my database on AWS over an SSH tunnel with Pandas

I am trying to query to my database running on AWS over an SSH tunnel with Pandas. But I fail login. Also there is one key that I use to connect on SQL client (Sequel Pro) that I don't know how to use in my python code.
This is the key: heroes-us-west-1-master.cheme3bzdejb.us-west-1.rds.amazonaws.com
This is my code:
with SSHTunnelForwarder(
(host, 22),
ssh_username=ssh_username,
ssh_private_key=ssh_private_key,
remote_bind_address=(localhost, 3306)
) as server:
conn = db.connect(host=localhost,
port=server.local_bind_port,
user=user,
passwd=password,
db=database)
return pd.read_sql_query(q, conn)
df = query("SELECT stores.name, stores.address\
FROM stores;")
This is the error message:
Traceback (most recent call last):
File "connection.py", line 32, in <module>
FROM stores;")
File "connection.py", line 22, in query
remote_bind_address=(localhost, 3306)
File "/Users/Solal/Desktop/SQL/venv/lib/python3.6/site-packages/sshtunnel.py", line 904, in __init__
logger=self.logger
File "/Users/Solal/Desktop/SQL/venv/lib/python3.6/site-packages/sshtunnel.py", line 1095, in _consolidate_auth
raise ValueError('No password or public key available!')
ValueError: No password or public key available!