I'm trying to setup my Flask application to work with a database hosted on a different server. My whole setup works, if i try to work with a simple PyMysql script i will be able to connect to the database, but when i try to do that from Flask i get any kind of problem.
I'm keeping my db configurations on config.py:
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://user:pass#external_ip/mydb'
But whenever i try to do a query, i will get the following error:
SELECT command denied to user 'user'#'local_ip'
So flask is looking for the db locally, for some reason, even though i set it to point to an external server. Can anyone help me out on this?
On the same environment, the following will connect and allow me to make queries:
connection = pymysql.connect(host='external_ip', user='user', password='pass', db='mydb', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)
This error looks more like a db server error, more then a local flask client error.
If it was a Flask local error of inability to connect to the mysql server you should end up with something like:
Unable to connect to the server
Hostname unreachable
Connection refused (if you reach the server but with the wrong port, for instance)
Reading this error I guess that you have reached the server, but for that user + IP + Database combination you have no read permissions.
See the GRANT Statement doc for further details
I'm trying to connect my database using SSL with PyMySQL, but I can't find good documentation on what the syntax is.
These credentials work in Workbench and with the CLI, but I get this error when using PyMySQL.
Can't connect to MySQL server on 'server.domain.com' ([WinError 10061] No connection could be made because the target machine actively refused it)")
db_conn = pymysql.connect(
host=db_creds['host'],
user=db_creds['user'],
passwd=db_creds['passwd'],
db=db_creds['db'],
charset=db_creds['charset'],
ssl={'ssl':{'ca': 'C:/SSL_CERTS/ca-cert.pem',
'key' : 'C:/SSL_CERTS/client-key.pem',
'cert' : 'C:/SSL_CERTS/client-cert.pem'
}
}
)
If I shut SSL off and drop the SSL parameter, I can connect unsecured just fine. What am I doing wrong with the SSL parameter?
Edit: PyMySQL now wants ssl parameters listed like this instead of in a dict.
db_conn = pymysql.connect(
host=db_creds['host'],
user=db_creds['user'],
passwd=db_creds['passwd'],
db=db_creds['db'],
charset=db_creds['charset'],
ssl_ca='C:/SSL_CERTS/ca-cert.pem',
ssl_key='C:/SSL_CERTS/client-key.pem',
ssl_cert='C:/SSL_CERTS/client-cert.pem'
)
Thanks for the help everyone. The syntax listed in the question is right, but the server I was attempting a connection to was using a non-standard port. I needed to add
port = db_creds['port']
Thanks, MannyKary, for the clue.
I had the same problem connecting pyMysql using client-side cert and key for users that REQUIRE X509, the TiDB (mySQL 5.7 compatible) server complained that no cert was supplied!!!
[2021/05/18 16:31:23.881 +00:00] [INFO] [privileges.go:258] ["ssl check failure, require x509 but no verified cert"] [user=mindline_root] [host=%]
Looking through the sourcecode of PyMysql 1.0.2, it appears that the ssl parameter is now a boolean instead of a ssl_dict, so you should put all your ssl parameters into individual arguements, e.g.,
db_conn = pymysql.connect(
host=db_creds['host'],
user=db_creds['user'],
passwd=db_creds['passwd'],
db=db_creds['db'],
charset=db_creds['charset'],
ssl_ca='C:/SSL_CERTS/ca-cert.pem',
ssl_key='C:/SSL_CERTS/client-key.pem',
ssl_cert='C:/SSL_CERTS/client-cert.pem'
)
I have installed two database server, MySQL and MongoDB. I have two functions written in Python 2.7 to connect to the databases, one for MySQL and one for MongoDB. Now, how do I know which database server is running on my localhost using python 2.7 so that i can call the appropriate connecting function?
Here is my connection function for both database servers:
import mysql.connector
from pymongo import MongoClient
conn=None
def mysql_make_connection():
global conn
conn=mysql.connector.connect(host='localhost',database='sk',user='root',password='SonuKumar#1')
if conn.is_connected():
print "Connection established"
else:
print "Connection Problem"
def mongo_make_connection():
global conn
conn=MongoClient('localhost')
Instead of checking to see which one is running, perhaps a better way would be to use a try/except block to connect to the one most likely to be running. If that fails connect to the other one. So if mysql is the one most likely to be running, it could be something like this:
try:
<code to connect to mysql>
except <connection error>:
<code to connect to mongodb>
I just started to learn python and try to connect to oracle 11g, but I always get following error
cx_Oracle.InternalError: No Oracle error?
Here is my simple script to connect to oracle
import cx_Oracle as oracle
con = oracle.connect('user/password#ip:port/service')
Already try to look for any reference in other sites including here but can't find the solution. I don't think I have connection issue to oracle, because I use the same PC to connect to oracle using PHP.
Any advise would be appreciated, thanks.
One thing to keep in mind anytime you work with Oracle is that they use a proprietary connection protocol TNS (Transparent Network Substrate).
Therefore, you might need to use the cx_Oracle.makedsn(ip, port, SID) method and then pass it to cx_Oracle.connect() method to create your connection. Thus the general format on how to set up Oracle connection is:
import cx_Oracle
ip = 'xxx.xxx.xx.xxx'
port = 'xxxx'
SID = 'SID'
username = 'username'
password = 'password'
dsn_tns = cx_Oracle.makedsn(ip, port, SID)
db = cx_Oracle.connect(username, password, dsn_tns)
This is assuming you have already gotten cx_Oracle to work and import properly, which can be finicky depending on your environment.
I'm having an issue connecting to my local MySQL database using Python's MySQLdb library. The script has been working well previously, but I will occasionally get the MySQL error in the title. There seems to be no explanation for when the error occurs, and the script is always run from the same machine with the same arguments.
The MySQL server is running as a service on Windows XP SP3 using port 3306 (locally hosted phpMyAdmin works), and the script is run from an Ubuntu 10.04 guest operating system in Oracle VM VirtualBox.
I am currently working around this issue by opening a command prompt and executing 'net stop MySQL' then 'net start MySQL'. This allows me to run the script a few times again before resulting in the error, which I've been fixing by restarting the MySQL service.
As I am still making changes to the script, there are occasions when the script raises an exception and doesn't exit gracefully, though I do catch the exception and close the cursor and connection.
The code to connect to the database:
def __init__(self):
try:
print "Connecting to the MySQL database..."
self.conn = MySQLdb.connect( host = "192.168.56.1",
user = "guestos",
passwd = "guestpw",
db = "testdb")
self.cursor = self.conn.cursor(MySQLdb.cursors.DictCursor)
print "MySQL Connection OK"
except MySQLdb.Error, e:
print "MySQLdb error %d: %s" % (e.args[0],e.args[1])
raise
The full error generated when this happens is as follows:
MySQLdb error 2013: Lost connection to MySQL server at 'reading initial communication packet', system error: 0
Traceback (most recent call last):
File "search.py", line 45, in <module>
dataHandler = DataHandler()
File "/home/guestos_user/workspace/Search/src/data_handler.py", line 25, in __init__
db = "testdb")
File "/usr/lib/pymodules/python2.6/MySQLdb/__init__.py", line 81, in Connect
return Connection(*args, **kwargs)
File "/usr/lib/pymodules/python2.6/MySQLdb/connections.py", line 170, in __init__
super(Connection, self).__init__(*args, **kwargs2)
_mysql_exceptions.OperationalError: (2013, "Lost connection to MySQL server at 'reading initial communication packet', system error: 0")
sudo vi /etc/mysql/my.cnf
delete
bind-address = 127.0.0.1
then
sudo reboot now
That's it. Be aware that this will make your mysql server less secure as you are exposing it.
I have seen this happen when child processes try to share the same mysql connection id (solution = create new connections for each child process). I'm not sure if this is also possible when sharing connection objects with multiple threads.
However, that's only one of the many possible causes. See VVS's answer in MySQL Error 2013 for a list of troubleshooting resources.
Do you have in your MySQL server an acount called guestos#YOURIPADDRESS?
You must have an account to access to your MySQL server from YOURIPADDRESS!
For example:
Your IP address is 192.168.56.2; then you must create and account if not exist to access.
mysql> create user guestos#192.168.56.2 identified by 'guestpw';
The problem fixed for me just by restarting my mac. Though there might be a more specific fix for it.
I received a similar error when attempting to connect to my MySQL server remotely through a user with the sufficient permissions.
After editing the /etc/mysql/my.cnf file to include
[mysqld]
bind-address=xx.xx.xxx.xxx
where xx.xx.xxx.xxx is my local IP address, I began experiencing the exact same error as you. From there, I found an answer regarding this issue (answered by Coffee Converter) which worked for me, and can be found here: Lost connection to MySQL server at 'reading initial communication packet', system error: 0 on a windows machine
All I did to fix the issue for myself was edit the /etc/hosts.allow to include
mysqld: ALL: allow
Works great now! I hope this helped :)
Could you change the bind-address=localhost and restart MySQL server? Seems like this issue is related to yours: http://forums.mysql.com/read.php?152,355740,355742#msg-355742
Also this-
If MySQL port is wrong result is MySQL client error 2013 "Lost
connection ...". Note that this error also occurs if port forwarding
is disabled in SSH configuration (the configuration parameter
'AllowTcpForwarding' is set to 'no' in the 'sshd_config' file). It
(here) simply tells that there is no connection from SSH to MySQL for
some reason. But the mySQL client API 'thinks' there was one
connection and that is why is says 'Lost connection ...' and not
'Can’t connect...'. There was one successful connection - but not to
the MySQL server - to the SSH daemon only! But the MySQL client API is
not designed to 'see' the difference!
Refer this.
I run a windows server and from time to time the php-win.exe will load and stay in the processes list on the windows task manager.
If you know the host file is correct, then kill the php-win.exe process and restart iis iisreset
If you are running windows then your problem should be solved.
I've had the exact same mysql error (ERROR 2013 (HY000): Lost connection to MySQL server at 'reading initial communication packet', system error: 0=) and have resolved it by adding a newline to /etc/hosts.deny.
Possibility: your database is corrupted.
I encountered this situation when I was running an UPDATE statement on a specific row of a specific table. (Specifically, I was editing an item in a Django Admin site.) Most of the time the database worked just fine.
I finally resolved the problem by running:
OPTIMIZE TABLE `your_table`
After that everything was OK, no connection lost.
Conclusion:
The problem "Lost connection to MySQL server at 'reading initial communication packet'", sometimes "Can't connect to MySQL server on '127.0.0.1'", could possibly be resolved by running a full database optimization if the database is corrupted. For more info, read this.
Just to further extend the list of possible causes: it could also be as banal as wrong connection data/credentials. I encountered this error in conjunction with sqlalchemy:
sqlalchemy.exc.OperationalError: (mysql.connector.errors.OperationalError) 2013 (HY000): Lost connection to MySQL server at 'reading initial communication packet', system error: 0
In my code I connect to several different databases and once in a while it happens that I don't get the mapping between the db connections and their credentials (e.g. ip address of server, db-name, password etc.) right, which then also results in the 2013-error (in this case wrapped into an sqlalchemy operational error).
setting.py file set like:
'ENGINE': 'django.db.backends.mysql',
'NAME': 'test2',
'USER': 'root',
'PASSWORD': '',
'HOST': 'localhost',
'PORT': '3308',
This bug report might be of interest to you. Don't know if this will help you, but some were able to solve it by using the name of the server rather than the ip address in the connection properties.