I'm trying to use MySQL Connection/Python to connect to my database.
Here's the output I'm getting:
Traceback (most recent call last):
File "bh2000.py", line 33, in <module>
cnx = mysql.connector.connect(**config)
File "/Library/Python/2.7/site-packages/mysql/connector/__init__.py", line 155, in connect
return MySQLConnection(*args, **kwargs)
File "/Library/Python/2.7/site-packages/mysql/connector/connection.py", line 123, in __init__
self.connect(**kwargs)
File "/Library/Python/2.7/site-packages/mysql/connector/connection.py", line 430, in connect
self._open_connection()
File "/Library/Python/2.7/site-packages/mysql/connector/connection.py", line 393, in _open_connection
self._socket.open_connection()
File "/Library/Python/2.7/site-packages/mysql/connector/network.py", line 375, in open_connection
errno=2003, values=(self.get_address(), _strioerror(err)))
mysql.connector.errors.InterfaceError: 2003: Can't connect to MySQL server on 'host xxx.db.1and1.com:3306' (8 nodename nor servname provided, or not known)
Here's the code I'm using:
import mysql.connector
cnx = mysql.connector.connect(user='xxx', password='xxx',
host='xxx.db.1and1.com',
database='xxx')
cnx.close()
Where am I going wrong?
Did you specify the correct port?
Is your MySQL server running?
Is a firewall blocking access?
Try removing anonymous user account from your MySQL server?
Default port if not specified is 3306. Otherwise there is nothing wrong with your code. The problem is with your MySQL server or the connection is being blocked by your firewall or the server firewall. Make sure port 3306 is open and not blocked.
db = mysql.connector.connect(user='xxx', password='xxx', host='xxx.db.1and1.com', port=3306)
I believe the answer is because the hosting service you use, 1and1.com, uses a firewall that blocks all outside access to their databases. You have to run the code from a url that they host or it will not work.
I use the same server and had to figure this out the hard way myself. Below is a copy of what they have on one of their pages:
Access to the database via your website/presence only Please always
establish the connection to your database via your website/presence.
For security reasons, it is not possible to access the database
directly, for example via your local computer (external ODBC
connection).
To protect your data, your MySQL database is located on a dedicated
database server that is protected by a firewall.
Add a port argument in the command.
cnx = mysql.connector.connect(user='myuser',
password='mypassword', host='localhost', port='3306', database='mydb')
I got the same error. Once crosscheck the details you have entered. The host must be in the format 127.0.0.1. There should not be any / after the url.
Use localhost instead of IP, if you are working on same server.
myConnection = mysql.connector.connect(user='uname', password='pass', host='localhost', port='3306', database='databasename')
Related
I am aware that this question has been asked multiple times, but I haven't found a question that pertains to the same issue I am dealing with. I have a MySQL database hosted on Google Cloud SQL. I am running a python script out of a Google Cloud VM to connect to the database to run queries. Everything used to run fine, but now I am getting the following error on my initial connection to the server.
File "/usr/local/lib/python3.5/dist-packages/pymysql/__init__.py", line 94, in Connect
return Connection(*args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/pymysql/connections.py", line 327, in __init__
self.connect()
File "/usr/local/lib/python3.5/dist-packages/pymysql/connections.py", line 597, in connect
self._get_server_information()
File "/usr/local/lib/python3.5/dist-packages/pymysql/connections.py", line 966, in _get_server_information
packet = self._read_packet()
File "/usr/local/lib/python3.5/dist-packages/pymysql/connections.py", line 656, in _read_packet
packet_header = self._read_bytes(4)
File "/usr/local/lib/python3.5/dist-packages/pymysql/connections.py", line 702, in _read_bytes
CR.CR_SERVER_LOST, "Lost connection to MySQL server during query")
pymysql.err.OperationalError: (2013, 'Lost connection to MySQL server during query')
And here is the code I am using to connect to the server
connection = pymysql.connect(host='127.0.0.1',
user='xxxxxx',
password='xxxxxx',
database='foobar',
cursorclass=pymysql.cursors.DictCursor,
max_allowed_packet=16777216,
connect_timeout=100)
Initially, my connection code did not have the max_allowed_packet and connect_timeout, and it was working fine. After some research into my issue, these seemed to resolve others' issues, but it hasn't resolved mine.
You must add wait_timeout and start by 10000 and then see.
The other will not help, but i added iy you have another timeout that will not be catch by connection and wait timeout
interactive_timeout Number of seconds the server waits for activity on an interactive connection before closing it
wait_timeout Number of seconds the server waits for activity on a connection before closing it
It seems
use a mysql command right after the connection
SET session wait_timeout=300;
I am trying to connect to remote mongodb, here the ssh access has a different username and password, And the mongodb has a different username and password.
I tried passing the username and password of ssh in ssh tunnel server, and the mongodb credentials in the client, but getting an error stating:
pymongo.errors.ServerSelectionTimeoutError: 127.0.0.1:27017: [Errno 111] Connection refused
Here the ssh connection is happening, whereas the mongodb is not getting connected
def Collect_Pid_DB():
MONGO_DB = "mydatabasename"
server = SSHTunnelForwarder(
(MONGO_HOST,22),
ssh_username=username,
ssh_password=password,
remote_bind_address=('127.0.0.1', 27017)
)
server.start()
#print (server)
uri = "mongodb://admin:" + urllib.quote("p#ssW0$3") + "#127.0.0.1:27017"
client = pymongo.MongoClient(uri,server.local_bind_port)
db = client[MONGO_DB]
print (db)
print(json.dumps(db.collection_names(), indent=2))
server.stop()
Actual results:
Database(MongoClient(host=['127.0.0.1:27017'], document_class=dict, tz_aware=False, connect=True), u'MissingPatches')
Traceback (most recent call last):
File "duplicate.py", line 7, in <module>
class MyClass:
File "duplicate.py", line 41, in MyClass
Collect_Pid_DB('192.142.123.142','root','password','mydatabasename')
File "duplicate.py", line 35, in Collect_Pid_DB
print(json.dumps(db.collection_names(), indent=2))
File "/usr/local/lib/python2.7/dist-packages/pymongo/database.py", line 787, in collection_names
nameOnly=True, **kws)]
File "/usr/local/lib/python2.7/dist-packages/pymongo/database.py", line 722, in list_collections
read_pref) as (sock_info, slave_okay):
File "/usr/lib/python2.7/contextlib.py", line 17, in __enter__
return self.gen.next()
File "/usr/local/lib/python2.7/dist-packages/pymongo/mongo_client.py", line 1135, in _socket_for_reads
server = topology.select_server(read_preference)
File "/usr/local/lib/python2.7/dist-packages/pymongo/topology.py", line 226, in select_server
address))
File "/usr/local/lib/python2.7/dist-packages/pymongo/topology.py", line 184, in select_servers
selector, server_timeout, address)
File "/usr/local/lib/python2.7/dist-packages/pymongo/topology.py", line 200, in _select_servers_loop
self._error_message(selector))
pymongo.errors.ServerSelectionTimeoutError: 127.0.0.1:27017: [Errno 111] Connection refused
The following is the working code for the above question, In the above code the issue was that the local bind port along with the url was not parsed into a proper format, hence when authenticating the port couldnt be authenticated in order to connect.
Hence in the above code mentioned in the question was not working.
The working code to connect to mongodb, when the ssh and mongo both have different credentials:
def Collect_Pid_DB(hostname,user,password,accountid):
server = SSHTunnelForwarder(
(MONGO_HOST,22),
ssh_username=MONGO_USER,
ssh_password=MONGO_PASS,
remote_bind_address=('127.0.0.1', 27017)
)
host_name="'primary_host_name': 'win-3auvcutkp34'"
patch_name="'patch_name': '[\\& A-Za-z0-9+.,\\-]+'"
server.start()
client = pymongo.MongoClient(host='127.0.0.1',
port=server.local_bind_port,
username='admin',
password='P#ssW0Rd')
db = client[MONGO_DB]
print (db)
print(json.dumps(db.collection_names(), indent=2))
Hope the above answer would be helpful to someone, as i couldn't find one anywhere when i needed :P
Try to pip install ssh-pymongo and then:
from ssh_pymongo import MongoSession
session = MongoSession(MONGO_HOST)
db = session.connection['mydatabasename']
# perform your queries #
session.stop()
If you have more complex settings, check docs for cases, e.g.:
from ssh_pymongo import MongoSession
session = MongoSession(
MONGO_HOST,
port=22,
user='ssh_username',
password='ssh_password',
uri='mongodb://admin:p#ssW0$3#127.0.0.1:27017')
db = session.connection['mydatabasename']
print(db.collection_names())
session.stop()
I am attempting to connect to an RDS instance using Python's pymysql library. Unfortunately I'm getting an exception back.
Here is my Python code:
import pymysql
#Connect
connection = pymysql.connect(host='jdbc:mysql://dbname.url.us-east-1.rds.amazonaws.com/dbname',
port='3306',
user='username',
password='pass',
database='dbname')
Upon executing it, I receive the following exception:
Traceback (most recent call last):
File "/path/to/file/test.py", line 8, in <module>
database='treemigodb')
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pymysql/__init__.py", line 94, in Connect
return Connection(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pymysql/connections.py", line 327, in __init__
self.connect()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pymysql/connections.py", line 629, in connect
raise exc
pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on 'jdbc:mysql://dbname.url.us-east-1.rds.amazonaws.com/dbname' ([Errno 8] nodename nor servname provided, or not known)")
Here is what I've tried:
I've opened up the security group on the AWS side to traffic. I had previously performed this connection in Java, with success. AWS is configured as it should be.
I've seen in other examples that the host format tends to vary. Therefore, I've tried:
jdbc:mysql://dbname.url.us-east-1.rds.amazonaws.com/dbname
jdbc:mysql://url.us-east-1.rds.amazonaws.com/dbname
jdbc:mysql://dbname.url.us-east-1.rds.amazonaws.com/
jdbc:mysql://url.us-east-1.rds.amazonaws.com/
dbname.url.us-east-1.rds.amazonaws.com/dbname
url.us-east-1.rds.amazonaws.com/dbname
dbname.url.us-east-1.rds.amazonaws.com/
Is there some potential setup that I could be missing? I've double-checked that every other parameter matches.
My summer project is to put data into SQL for processing. Unfortunately I can not establish a connection to the SQL with mysql connector.
The python file I am testing with are two lines:
import mysql.connector
db1 = mysql.connector.connect(host="localhost", database="thename", user="user",password="passw")
The error message is:
C:\Projekt\Python efforts...>test.py Traceback (most recent call
last): File
"C:\Users\Niklas\AppData\Local\Programs\Python\Python35\lib\site-packages\mysql\connector\network.py",
line 472, in open_connection
self.sock.connect(sockaddr) ConnectionRefusedError: [WinError 10061] Det gick inte att göra en anslutning eftersom måldatorn aktivt
nekade det
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File "C:\Projekt\Python
efforts...\test.py", line 4, in
db1 = mysql.connector.connect(host="localhost", database="thename", user="user",password="passw") File
"C:\Users\Niklas\AppData\Local\Programs\Python\Python35\lib\site-packages\mysql\connector__init__.py",
line 179, in connect
return MySQLConnection(*args, **kwargs) File "C:\Users\Niklas\AppData\Local\Programs\Python\Python35\lib\site-packages\mysql\connector\connection.py",
line 95, in init
self.connect(**kwargs) File "C:\Users\Niklas\AppData\Local\Programs\Python\Python35\lib\site-packages\mysql\connector\abstracts.py",
line 719, in connect
self._open_connection() File "C:\Users\Niklas\AppData\Local\Programs\Python\Python35\lib\site-packages\mysql\connector\connection.py",
line 206, in _open_connection
self._socket.open_connection() File "C:\Users\Niklas\AppData\Local\Programs\Python\Python35\lib\site-packages\mysql\connector\network.py",
line 475, in open_connection
errno=2003, values=(self.get_address(), _strioerror(err))) mysql.connector.errors.InterfaceError: 2003: Can't connect to MySQL
server on 'localhost:3306' (10061 Det gick inte att göra en anslutning
eftersom måldatorn aktivt nekade det)
C:\Projekt\Python efforts...>
I have tried restarting and enabling services and computer several times. The user and password I use grants me access in SQL Server Management Studio. I have created a firewall rule to allow communication on port 3306, though it is not listed as one of the active ports when I look. I have also tried disabling the firewall on my computer (though not on the router as it should not be needed for a localhost query?). Using wireshark I don't seem to get any traffic at all on port 3306(!?). I cannot telnet to localhost though tracert has no problems. I have tried with different IPs and domain name that are valid. I have enabled TCP/IP settings for a bunch of the different IP versions under TCP/IP protocol in the SQL Server Configuration manager (though I'm not sure how I did that as it is write protected so I can't do the rest of them).
Everything listed here yields the same result so I assume that there is something very fundamentally (basic and easy?) wrong with what i am doing. Please pitch in with any and all troubleshooting tips you can find for resolving this connection issue as I am on my third day of getting absolutely nowhere.
Once again it has been proven that it is easy to get blinded when digging. I was trying to use mysql connector to connect to a ms sql. I have now switched to pypyodbc to handle the communication with the SQL.
I'm not really sure what to do here. I'm trying to connect to MySQL Community Server by using a python script, and I'm running into an error message. This is being run on OS X Yosemite. I'm using the PyMySQL module, which imports correctly. The line
con = pms.connect(host='localhost',user='jaxon',passwd='password')
throws the following error message:
Traceback (most recent call last):
File "/Users/icefreak21/Documents/Python Files/DBConnector.py", line 4, in <module>
con = pms.connect(host='127.0.0.1',user='root',passwd='c0c0_puFF')
File "/Users/icefreak21/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/pymysql/__init__.py", line 88, in Connect
return Connection(*args, **kwargs)
File "/Users/icefreak21/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/pymysql/connections.py", line 644, in __init__
self._connect()
File "/Users/icefreak21/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/pymysql/connections.py", line 869, in _connect
raise exc
pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on 'localhost' ([Errno 61] Connection refused)")
I've searched around on the site and haven't found a question that details this particular situation. As far as I can tell, the server is running; the kicker is that I have no problem connecting through the command line with the same host, user, and password. I've tried switching the host name to '127.0.0.1' and I've tried specifying the port number (3306).
I found one solution that suggested specifying the socket, but when I ran the suggested code
./mysqladmin variables | grep socket
to find the socket file to specify, I get the following error code:
./mysqladmin: connect to server at 'localhost' failed
error: 'Access denied for user 'jaxon'#'localhost' (using password: NO)'
Does anyone have any other suggestions?
I had the same problem. I solved it by changing the port. You can add your port like this:
3307(port = 3307)
I'm recommending this because the mysql port of mac vision might be 3307.