Python Not Executing MySQLdb connect - python

I am having some issues connecting to my hosted mysql database using python. My code is as follows:
import MySQLdb
db = MySQLdb.connect(host="xxxxxx.db.1and1.com", user="xxxxxxx",passwd="xxxxxxx", db="xxxxxxx")
I get the following error:
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
db = MySQLdb.connect(host="db518597727.db.1and1.com", user="dbo518597727", passwd="OilyOily123", db="db518597727")
File "C:\Python27\lib\site-packages\MySQLdb\__init__.py", line 81, in Connect
return Connection(*args, **kwargs)
File "C:\Python27\lib\site-packages\MySQLdb\connections.py", line 193, in __init__
super(Connection, self).__init__(*args, **kwargs2)
OperationalError: (2003, "Can't connect to MySQL server on 'xxxxxxx.db.1and1.com' (10060)")
My sql database is hosted by 1and1. I am sure I have the right credentials, as when I read from this database on a php website, using the same credentials (I have triple checked) it works fine.
I have tried this both on a Raspberry Pi (where I intend to use it) and on my Windows 8.1 PC, so I am pretty sure that it is not the computer that is the problem.
Any help would be much appreciated.Many thanks.

In MySQL credentials are per client, so we distinguish a couple of client types:
- localhost means the same machine as MySQL server connecting via Unix Socket
- 127.0.0.1 means the same machine as MySQL server connecting via TCP/IP
- A.B.C.D where letters are replaced by numbers in range 0-255 which means IP address of client machine connecting via TCP/IP
- * is a wildcard which means that any client can connect with given credentials via TCP/IP
Every entry in MySQL users table consists of client specification (described above), username, password and some other columns (not relevant here).
So the problem you are facing is that PHP script on 1and1 server can connect to the database hosted on 1and1 since the hosting company sets up their database server to accept connections from their own servers with valid credentials.
But the same credentials are considered invalid for connections coming from client machines unknown to 1and1.
What you can do is to ask 1and1 to give your specific IP access rights to your database.
What you can't to is to overcome this problem on your own.

Related

pymongo.errors.ConfigurationError: All nameservers failed to answer the query _mongodb._tcp.******.gcp.mongodb.net. IN SRV: [duplicate]

i can connect locally to my mongodb server with the address 0.0.0.0/0. However, when I deploy my code to the cloud I get the error deploy to google cloud function.
google cloud function with python 3.7 (beta)
atlas mongo db
python lib:
-pymongo
-dnspython
Error: function crashed. Details:
All nameservers failed to answer the query _mongodb._tcp.**-***.gcp.mongodb.net. IN SRV: Server ***.***.***.*** UDP port 53 answered SERVFAIL
Traceback (most recent call last): File "/env/local/lib/python3.7/site-packages/pymongo/uri_parser.py", line 287, in _get_dns_srv_hosts results = resolver.query('_mongodb._tcp.' + hostname, 'SRV') File "/env/local/lib/python3.7/site-packages/dns/resolver.py", line 1132, in query raise_on_no_answer, source_port) File "/env/local/lib/python3.7/site-packages/dns/resolver.py", line 947, in query raise NoNameservers(request=request, errors=errors) dns.resolver.NoNameservers: All nameservers failed to answer the query _mongodb._tcp.**mymongodb**-r091o.gcp.mongodb.net. IN SRV: Server ***.***.***.*** UDP port 53
finally after stuck 2 day, goblok banget semaleman
just change connection
from
SRV connection string (3.6+ driver)
to
Standard connection string (3.4+ driver)
mongodb://<USERNAME>:<PASSWORD>#<DATABASE>-shard-00-00-r091o.gcp.mongodb.net:27017,<COLLECTION>-shard-00-01-r091o.gcp.mongodb.net:27017,<COLLECTION>-shard-00-02-r091o.gcp.mongodb.net:27017/test?ssl=true&replicaSet=<COLLECTION>-shard-0&authSource=admin&retryWrites=true
or you can see your connection string in atlas mongodb.
idk why can`t connect with srv connection string in google cloud functions, maybe not suppot now, or just misconfiguration.
This might help somone, I've struggled with this error on Windows when I tried to connect to MongoDB with the mongodb+srv:// syntax, it worked fine if I try it through WSL or on a Linux machine.
From https://forum.omz-software.com/topic/6751/pymongo-errors-configurationerror-resolver-configuration-could-not-be-read-or-specified-no-nameservers/4
import dns.resolver
dns.resolver.default_resolver=dns.resolver.Resolver(configure=False)
dns.resolver.default_resolver.nameservers=['8.8.8.8'] # this is a google public dns server, use whatever dns server you like here
# as a test, dns.resolver.query('www.google.com') should return an answer, not an exception
Most of the time the error occurs when your network isn't configured with 8.8.8.8 DNS Adress.
Type the following command on command prompt to verify
ipconfig /all
check your IP configuration & in the config you should see the following
DNS Servers . . . . . . . . . . . : 8.8.8.8
8.8.4.4
if not you should configure your network using 8.8.8.8 as primary DNS and 8.8.4.4 as secondary.
OR
May be you are using a VPN or private DNS.In that case contact you service provider for the assistance.

OperationalError: (2003, "Can't connect to MySQL server on 'mysql2.000webhost.com' (10060)")

I have been learning some basic MySQL and decided to put it into Python which i have some more experience in. I have got PHP scripts working on this MySQL server so i know the server is working. But every time i connect i get this error:
Traceback (most recent call last):
File "E:/Geekster_Bot/Geekster_Bot Code/Geekster_Bot_alpha_API_MySQL", line 6, in <module>
db="MY DATABASE")# name of the data base
File "C:\Python27\lib\site-packages\MySQLdb\__init__.py", line 81, in Connect
return Connection(*args, **kwargs)
File "C:\Python27\lib\site-packages\MySQLdb\connections.py", line 187, in __init__
super(Connection, self).__init__(*args, **kwargs2)
OperationalError: (2003, "Can't connect to MySQL server on 'mysql2.000webhost.com' (10060)")
Im really not sure why. I have got the MySQL port (3306) open and like i said, the server/database is working. Any ideas?
This is the code of the entire MySQL connection;
import MySQLdb
db = MySQLdb.connect(host="mysql2.000webhost.com", # your host, usually localhost
user="MY USER", # your username
passwd="MY PASSWORD", # your password
db="MY DATABASE")# name of the data base
#you must create a Cursor object. It will let
#you execute all the queries you need
cur = db.cursor()
#Use all the SQL you like
cur.execute("SELECT * twitch_follows_ign")
#print all the first cell of all the rows
for row in cur.fetchall() :
print row[0]
All the blocked out data is entered correctly.
Your database seems to be on an external server "mysql2.000webhost.com", before you connect to the MySQL server from your Python application you'll have to create a database user and grant that user access to the server from your IP address.
If you have a free account on "000webhost" you probably won't be able to create a database user that has access to the database from the outside.
Try this site http://www.freemysqlhosting.net/ they will grant you access to the newly created database from any IP address.

Can't connect to local MySQL server through socket '/opt/local/var/run/mysql55/mysqld.sock' (2) [duplicate]

I'm having trouble with the MySQLdb module.
db = MySQLdb.connect(
host = 'localhost',
user = 'root',
passwd = '',
db = 'testdb',
port = 3000)
(I'm using a custom port)
the error I get is:
Error 2002: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)
Which doesn't make much sense since that's the default connection set in my.conf.. it's as though it's ignoring the connection info I give..
The mysql server is definitely there:
[root#baster ~]# mysql -uroot -p -P3000
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 19
Server version: 5.0.77 Source distribution
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql> use testdb;
Database changed
mysql>
I tried directly from the python prompt:
>>> db = MySQLdb.connect(user='root', passwd='', port=3000, host='localhost', db='pyneoform')
Traceback (most recent call last):
File "", line 1, in
File "/usr/lib64/python2.5/site-packages/MySQLdb/__init__.py", line 74, in Connect
return Connection(*args, **kwargs)
File "/usr/lib64/python2.5/site-packages/MySQLdb/connections.py", line 169, in __init__
super(Connection, self).__init__(*args, **kwargs2)
_mysql_exceptions.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)")
>>>
I'm confused... :(
Changing localhost to 127.0.0.1 solved my problem using MySQLdb:
db = MySQLdb.connect(
host = '127.0.0.1',
user = 'root',
passwd = '',
db = 'testdb',
port = 3000)
Using 127.0.0.1 forces the client to use TCP/IP, so that the server listening to the TCP port can pickle it up. If host is specified as localhost, a Unix socket or pipe will be used.
add unix_socket='path_to_socket' where path_to_socket should be the path of the MySQL socket, e.g. /var/run/mysqld/mysqld2.sock
Make sure that the mysql server is listening for tcp connections, which you can do with netstat -nlp (in *nix). This is the type of connection you are attempting to make, and db's normally don't listen on the network by default for security reasons. Also, try specifying --host=localhost when using the mysql command, this also try to connect via unix sockets unless you specify otherwise. If mysql is not configured to listen for tcp connections, the command will also fail.
Here's a relevant section from the mysql 5.1 manual on unix sockets and troubleshooting connections. Note that the error described (2002) is the same one that you are getting.
Alternatively, check to see if the module you are using has an option to connect via unix sockets (as David Suggests).
I had this issue where the unix socket file was some place else, python was trying to connect to a non-existing socket. Once this was corrected using the unix_socket option, it worked.
Mysql uses sockets when the host is 'localhost' and tcp/ip when the host is anything else. By default Mysql will listen to both - you can disable either sockets or networking in you my.cnf file (see mysql.com for details).
In your case forget about the port=3000 the mysql client lib is not paying any attention to it since you are using localhost and specify the socket as in unix_socket='path_to_socket'.
If you decided to move this script to another machine you will need to change this connect string to use the actual host name or ip address and then you can loose the unix_socket and bring back the port. The default port for mysql is 3306 - you don't need to specify that port but you will need to specify 3000 if that is the port you are using.
As far as I can tell, the python connector can ONLY connect to mysql through a internet socket: unix sockets (the default for the command line client) is not supported.
In the CLI client, when you say "-h localhost", it actually interprets localhost as "Oh, localhost? I'll just connect to the unix socket instead", rather than the internet localhost socket.
Ie, the mysql CLI client is doing something magical, and the Python connector is doing something "consistent, but restrictive".
Choose your poison. (Pun not intended ;) )
Maybe try adding the keyword parameter unix_socket = None to connect()?

MySQL error: 2013, "Lost connection to MySQL server at 'reading initial communication packet', system error: 0"

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.

Accessing a XAMPP mysql via Python

I'm attempting to use mysql after only having worked with sqlite in the past.
I've installed XAMPP on Linux (ubuntu) and have mysql up and running fine (seems like that with phpMyadmin at least). However, I'm having trouble getting the MySQLdb (the python lib) working {installed this using apt}.
to be exact:
>>> import MySQLdb
>>> db = MySQLdb.connect(host="localhost",db="opfine")
Traceback (most recent call last):
File "<input>", line 1, in <module>
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)
OperationalError: (2002, "Can't connect to local MySQL server through
socket '/var
/run/mysqld/mysqld.sock' (2)")
I'm guessing
Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock
means its expecting some sort of local installation (i.e. not within XAMPP), but I can't figure out how to go about modding this to get it to work with the XAMMP flavor of mysql.
Help is much appreciated!
For the record (and thanks to a pointer from Igancio), I found that the below works (terrible I didn't think of this before):
db=MySQLdb.connect(
user="root"
,passwd=""
,db="my_db"
,unix_socket="/opt/lampp/var/mysql/mysql.sock")
It means that you didn't start the MySQL server, or it's configured to not use a domain socket.
Have the same issue using and look for your SQL configuration file my.cnf.
# The following options will be passed to all MySQL clients
[client]
#password = your_password
port = 3306
socket = /Applications/XAMPP/xamppfiles/var/mysql/mysql.sock
and use socket as parameter:
mysql://read:read#localhost/phonehome?unix_socket=/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock
In my case:
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://read:read#localhost/phonehome?unix_socket=/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock'

Categories