Connect to MariaDB database on Synology NAS from SQLalchemy in python issue - python

furthering my question here, I am trying to put this question in a simpler way.
Following this tutorial, I am trying to start a connection to my Mariadb database in my NAS with SQLalchemy remotely. Here is the code:
# Module Imports
import mariadb
import sys
user = "my_name"
passwd = "my_pass"
host = "192.168.1.111"
db = "test"
port= "3307"
# Connect to MariaDB Platform
try:
conn = mariadb.connect(
user=user,
password=passwd,
host=host,
port=3307,
database=db
)
except mariadb.Error as e:
print(f"Error connecting to MariaDB Platform: {e}")
sys.exit(1)
# Get Cursor
cur = conn.cursor()
then I get this error:
ERROR:root:Internal Python error in the inspect module.
Below is the traceback from this internal error.
Error connecting to MariaDB Platform: Can't connect to server on '192.168.1.111' (36)
Traceback (most recent call last):
File "/var/folders/r5/wq0wq8mx0d56rbrbs38jt94w0000gn/T/ipykernel_39174/3834131737.py", line 14, in <module>
conn = mariadb.connect(
mariadb.OperationalError: Can't connect to server on '192.168.1.111' (36)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/user/miniforge3/lib/python3.9/site-packages/IPython/core/interactiveshell.py", line 3444, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "/var/folders/r5/wq0wq8mx0d56rbrbs38jt94w0000gn/T/ipykernel_39174/3834131737.py", line 24, in <module>
sys.exit(1)
SystemExit: 1
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/user/miniforge3/lib/python3.9/site-packages/IPython/core/ultratb.py", line 1101, in get_records
return _fixed_getinnerframes(etb, number_of_lines_of_context, tb_offset)
File "/Users/user/miniforge3/lib/python3.9/site-packages/IPython/core/ultratb.py", line 248, in wrapped
return f(*args, **kwargs)
File "/Users/user/miniforge3/lib/python3.9/site-packages/IPython/core/ultratb.py", line 281, in _fixed_getinnerframes
records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
File "/Users/user/miniforge3/lib/python3.9/inspect.py", line 1541, in getinnerframes
frameinfo = (tb.tb_frame,) + getframeinfo(tb, context)
AttributeError: 'tuple' object has no attribute 'tb_frame'
I have brew installed mariadb-connector-cand ;
brew installed mariadb; and
pip installed PyMySQL.
Would anyone please help?

I echo with #Tim Roberts. Go to your NAS "Installed Package", click the MariaDB 10 app. In it please make sure the databases are sharable over the intranet or internet. It is called TCP/IP connection. Check it and your connection will be working.
This is a point lots of people forget about when they first start up Mariadb.

Related

How to Handel exception during Mysql 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")

MySQL and Python Connector Test Errors

I am connecting, or trying to, MySQL and Python via PyCharm and I input the code that I was given and I am getting several errors that I am unable to resolve. Is there a pro out there that can assist?
Here is the code:
import mysql.connector
from mysql.connector import errorcode
config = {
"user": "movies_user",
"password": "popcorn",
"host": "127.0.0.1",
"database": "movies",
"raise on warnings": True
}
try:
db = mysql.connector.connect(**config)
print("\n Database user {} connected to MySQL on host {} with database {}".format(config["user"], config["host"],
config["database"]))
input("\n\n Press any key to continue...")
except mysql.connector as Error:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print(" The supplied username or password are invalid")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print(" The supplied database does not exist")
else:
print(err)
finally:
db.close()
And here are the errors:
Traceback (most recent call last):
File "C:\Users\Ryan\PycharmProjects\CSD_310\venv\lib\site-packages\mysql\connector\connection.py", line 353, in config
DEFAULT_CONFIGURATION[key]
KeyError: 'raise on warnings'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Ryan\PycharmProjects\CSD_310\mysql_test.py", line 14, in <module>
db = mysql.connector.connect(**config)
File "C:\Users\Ryan\PycharmProjects\CSD_310\venv\lib\site-packages\mysql\connector\__init__.py", line 159, in connect
return MySQLConnection(*args, **kwargs)
File "C:\Users\Ryan\PycharmProjects\CSD_310\venv\lib\site-packages\mysql\connector\connection.py", line 129, in __init__
self.connect(**kwargs)
File "C:\Users\Ryan\PycharmProjects\CSD_310\venv\lib\site-packages\mysql\connector\connection.py", line 449, in connect
self.config(**kwargs)
File "C:\Users\Ryan\PycharmProjects\CSD_310\venv\lib\site-packages\mysql\connector\connection.py", line 355, in config
raise AttributeError("Unsupported argument '{0}'".format(key))
AttributeError: Unsupported argument 'raise on warnings'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Ryan\PycharmProjects\CSD_310\mysql_test.py", line 20, in <module>
except mysql.connector as Error:
TypeError: catching classes that do not inherit from BaseException is not allowed
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Ryan\PycharmProjects\CSD_310\mysql_test.py", line 30, in <module>
db.close()
NameError: name 'db' is not defined
Process finished with exit code 1
I feel like I have tried everything that I can possibly find on Google. Any help is much appreciated!
I have tried the above code and I have tried resolving the errors to no avail.

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

Class com.teradata.jdbc.TeraDriver not found (Python, jaydebeapi module)

I am trying to connect to teradata using jaydebeapi.
import jaydebeapi
conn = jaydebeapi.connect('com.teradata.jdbc.TeraDriver',
'jdbc:teradata://serverIP/charset=UTF8,DBS_PORT=1025',
{'user': 'xxx', 'password': 'xxx'},
[r'path_to_teradata_jdbc_driver/tdgssconfig.jar',r'path_to_teradata_jdbc_driver/terajdbc4.jar'])
When I run this script ($python "Run SQL_Java.py") I get the following error:
Traceback (most recent call last): File "Run SQL_Java.py", line 60,
in
[r'path_to_teradata_jdbc_driver/tdgssconfig.jar',r'path_to_teradata_jdbc_driver/terajdbc4.jar'])
File
"/Users/xxx/anaconda/lib/python2.7/site-packages/jaydebeapi/init.py",
line 381, in connect
jconn = _jdbc_connect(jclassname, url, driver_args, jars, libs) File
"/Users/xxx/anaconda/lib/python2.7/site-packages/jaydebeapi/init.py",
line 190, in _jdbc_connect_jpype
jpype.JClass(jclassname) File "/Users/i.otenko/anaconda/lib/python2.7/site-packages/jpype/_jclass.py",
line 55, in JClass
raise _RUNTIMEEXCEPTION.PYEXC("Class %s not found" % name) jpype._jexception.RuntimeExceptionPyRaisable:
java.lang.RuntimeException: Class com.teradata.jdbc.TeraDriver not
found
Am I not specifying path to JDBC drivers correctly?
Try this variant code:
import jaydebeapi
USERNAME="user01"
PASSWORD="password01"
URL_CONNECTION="jdbc:teradata://server01/"
jars=['E:\\jdbc\\tdgssconfig.jar','E:\\jdbc\\terajdbc4.jar']
conn = jaydebeapi.connect('com.teradata.jdbc.TeraDriver', URL_CONNECTION,[USERNAME,PASSWORD], jars)
p.s. likely problem in [r'path_to_teradata_jdbc_driver/tdgssconfig.jar',r'path_to_teradata_jdbc_driver/terajdbc4.jar']

Connection to remote MySQL db from Python 3.4

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.

Categories