Connection refused to Postgresql - python

Here is the code I wrote for connecting Postgresql using psycopg2. My psql and pgadminIII is also running.
import psycopg2
connection = psycopg2.connect(dbname="gps_heatmap",user="postgres",host="localhost",password="1234")
cursor = connection.cursor()
cursor.execute("DROP TABLE IF EXISTS roads")
cursor.execute("CREATE TABLE roads (" +
"id SERIAL PRIMARY KEY," +
"name VARCHAR," +
"centerline GEOMETRY)")
cursor.execute("CREATE INDEX ON roads USING GIST(centerline)")
connection.commit()
But following error comes:
OperationalError Traceback (most recent call last)
<ipython-input-14-03e3f214b83e> in <module>()
1 import psycopg2
2
----> 3 connection = psycopg2.connect(dbname="gps_heatmap",user="postgres",host="localhost",password="1234",port="5432")
4 cursor = connection.cursor()
5
C:\Users\*******\Anaconda3\lib\site-packages\psycopg2\__init__.py in connect(dsn, database, user, password, host, port, connection_factory, cursor_factory, async, **kwargs)
162 for (k, v) in items])
163
--> 164 conn = _connect(dsn, connection_factory=connection_factory, async=async)
165 if cursor_factory is not None:
166 conn.cursor_factory = cursor_factory
OperationalError: could not connect to server: Connection refused (0x0000274D/10061)
Is the server running on host "localhost" (::1) and accepting
TCP/IP connections on port 5432?
could not connect to server: Connection refused (0x0000274D/10061)
Is the server running on host "localhost" (127.0.0.1) and accepting
TCP/IP connections on port 5432?
I edited the pg_hbf.conf as:
host all all 0.0.0.0/0 md5
Again,same error repeated

Clarification
The answer below was accepted, however, it was not the solution to the problem... the problem was that the postgresql server was configured for port 5433, not the default port of 5432. This should fix the problem:
connection = psycopg2.connect(database="gps_heatmap", user="postgres", password="1234", host="localhost", port=5433)
Original answer
Try replacing dbname="gps_heatmap" with database="gps_heatmap" as the former is intended for use within a connection string and the latter when keyword arguments are passed to psycopg2.connect():
connection = psycopg2.connect(database="gps_heatmap", user="postgres", host="localhost", password="1234")
Or you could use a connection string:
connection = psycopg2.connect("dbname=gps_heatmap user=postgres host=localhost password=1234")

What worked for me was to open Services (search it in Windows), and then look for the postgres service: postgresql-x64-10 in my case.
Run the service
Restart the service
After that, the error was gone.
My error originated by installing MySQL after PostgreSQL, I guess there was a change in the ports or something, but this fixed it.

changed my IDE to Atom or use pycharm and there was no longer an error you can check the port also

Related

PyMySQL using localhost vs socket incoherant behaviour

I am using PyMySQL to connect to a database running on localhost. I can access the database just fine using the username/password combiunation in both the command line and adminer so the database does not appear to be the probem here.
My code is as follow. However, when using the host="127.0.0.1" options, I get an OperationalError and an Errno 111. Using the same code, but connecting via the socket Mariadb runs on is fine.
import pymysql.cursors
from pprint import pprint
# This causes an OperationalError: (pymysql.err.OperationalError) (2003, "Can't connect to MySQL server on 'localhost' ([Errno 111] Connection refused)")
# connection = pymysql.connect(
# host="127.0.0.1",
# port=3306,
# user="root",
# password="S3kr37",
# db="my_test",
# )
# This works.
connection = pymysql.connect(
user="root",
password="S3kr37",
db="my_test",
unix_socket="/var/lib/mysql/mysql.sock"
)
try:
with connection.cursor() as cursor:
sql = "select * from MySuperTable"
cursor.execute(sql)
results = cursor.fetchall()
pprint(results)
finally:
connection.close()
What am I doing wrong?
PS: Note that this question has the same problem but the solution offered is the socket. That is no good enough: I want to know why I cannot use the hostname as the documentation suggests.
Errorcode 2003 (CR_CONN_HOST_ERROR) is returned by the client library, in case the client wasn't able to establish a tcp connection to the server.
First you should check, if you can connect via telnet or mysql command line client to your server.
If not, check the server configuration file:
does the server run on port 3306?
is IPv4 disabled?
is skip-networking enabled?
is bind-address activated (with another IP?

Python - MySQL connection error

I use Python 3.5.2 and PyMySQL
and after creating the database of MySQL
import pymysql
conn = pymysql(host='127.0.0.1',unix_socket='/tmp/mysql.sock',user='root',passwd=None,db='mysql')
AttributeError: module 'socket' has no attribute 'AF_UNIX'
p.s. when setting MySQL in my win10,the port 3306 can't work(make me unable to continue)
so I change the port to 306 and then work
Has that any impact on my error?
it shows some error...
If you are running on Windows, you cannot use a Unix socket to connect to the database. When connecting, set the host and port parameters instead of unix_socket.
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='Your password', db='mysql')

pyodbc connecting to SQL Server 2012 problems

Below is the traceback. I've read all the other SO threads, googled for over two hours, and cannot figure this out. Here is what I have tried:
Both SQL Authentication and Windows Authentication versions of the connection string.
Using the SQL Server name (text) and also the IP Address of the server
Including and Excluding port 1443 (the default tcp/ip port for the SQL server)
Creating new rules in Windows Firewall to allow both inbound/outbound TCP at port 1443
List item
Traceback (most recent call last):
File "pythonscript.py", line 75, in
conn = pyodbc.connect(driver='{SQL Server}', server='ipaddress,1443', database='master', uid='XYZ\login', pwd='password')
pyodbc.Error: ('08001', '[08001] [Microsoft][ODBC SQL Server Driver][DBNETLIB]SQL Server does not exist or access denied. (17) (SQLDriverConnect); [01000] [Microsoft][ODBC SQL Server Driver][DBNETLIB]ConnectionOpen (Connect()). (53)'
here are some examples of what I've tried for the connection string:
conn = pyodbc.connect('Trusted_Connection=yes', driver = '{SQL Server}',server = '1.1.1.1,1443', database = 'master')
then
conn = pyodbc.connect(driver='{SQL Server}', server='1.1.1.1,1443', database='master', uid='xyz\login', pwd='pwd'
then I also tried both of the above with the name of the server (text) rather than the IP address. I have no idea how to get this to work at this point.
Have you confirmed you have connectivity between the servers? Try telnet -
telnet serverName 1433
If that connects then you can focus on issues with Python or the connection string.
In your connection string change it to use the PORT parameter instead of the ,1433. Something like -
SERVER=1.1.1.1;PORT=1433;
I would also say you might be better off passing the whole string. Here is what I do on Linux using FreeTDS typically -
self.db_connection = pyodbc.connect("DRIVER=FreeTDS;SERVER=1.1.1.1;PORT=1433;DATABASE=myDB;UID=myUser;PWD=myPass;TDS_Version=8.0;")
CONNECTION FROM WINDOWS TO MS SQL SERVER DATABASE:
Here you have an example I use myself to connect to MS SQL database table with a Python script:
import pyodbc
server = 'ip_database_server'
database = 'database_name'
username = 'user_name'
password = 'user_password'
driver = '{SQL Server}' # Driver you need to connect to the database
port = '1433'
cnn = pyodbc.connect('DRIVER='+driver+';PORT=port;SERVER='+server+';PORT=1443;DATABASE='+database+';UID='+username+
';PWD='+password)
cursor = cnn.cursor()
If you are trying to connect from a Windows device to the DB, go to ODBC Data Source Administrator from Windows, and check if you have installed the driver:
Where is the ODBC data source administrator in a Windows machine.
The image is in spanish, but you only have to click on 'Drivers' tab, and check if the driver is there as in the image.
CONNECTION FROM LINUX/UNIX TO MS SQL SERVER DATABASE:
If you are working in Linux/Unix, then you shoud install a ODBC manager like 'FreeTDS' and 'unixODBC'. To configure them, you have some examples in the following links:
Example: Connecting to Microsoft SQL Server from Linux/Unix
Example: Installing and Configuring ODBC

PyMySQL can't connect to MySQL on localhost

I'm trying to connect to MySQL on localhost using PyMySQL:
import pymysql
conn = pymysql.connect(db='base', user='root', passwd='pwd', host='localhost')
but (both on Python 2.7 and Python 3.2) I get the error:
socket.error: [Errno 111] Connection refused
pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on 'localhost' (111)")
I'm sure mysqld is running because I can connect using mysql command or phpMyAdmin. Moreover, I can connect using MySQLdb on Python 2 with nearly the same code:
import MySQLdb
conn = MySQLdb.connect(db='base', user='root', passwd='pwd', host='localhost')
It seems that the problem is on PyMySQL side rather than MySQL but I have no idea how to solve it.
Two guesses:
Run mysqladmin variables | grep socket to get where the socket is located, and try setting up a connection like so:
pymysql.connect(db='base', user='root', passwd='pwd', unix_socket="/tmp/mysql.sock")
Run mysqladmin variables | grep port and verify that the port is 3306. If not, you can set the port manually like so:
pymysql.connect(db='base', user='root', passwd='pwd', host='localhost', port=XXXX)
Seems like changing localhost to 127.0.0.1 fixes the error, at least in my configuration.
If it doesn't, I would look for errors in tcp sockets connection and, of course, post it as a bug in pymysql bugtrack.
I solved the issue by replacing localhost with 127.0.0.1 and changing the password to my MYSQL database password as shown below;
conn = pymysql.connect(
host = '127.0.0.1',
port = 3306,
user = 'root',
passwd = 'XXXXXXXXX',
db = 'mysql'
)
I met the same question and my solution is as follows:
Run ssh -fN -L 3307:mysql_host:3306 ssh_user#ssh_host in my terminal.
Then input your ssh password
conn = pymysql.connect(db='base', user='root', passwd='pwd', host='localhost')
This error occurs because database does not support link directly.
I asked why socket worked but not TCP and the answer was that bind-address in /etc/my.cnf was not set correctly. This could be your problem too since the socket methods works just fine but the TCP one does not.
Those who are strugging to connect localhost MySQL from dockerised flask-sqlalchemy or using pymysql, pls look into this thread, very usefull How to connect locally hosted MySQL database with the docker container
This worked for me:
import pymysql
db = pymysql.connect(host="localhost",port=8889,user="root",passwd="root")
cursor=db.cursor()
cursor.execute("SHOW DATABASES")
results=cursor.fetchall()
for result in results:
print (result)
if you want to find the port # go to mysql in terminal, and type:
SHOW VARIABLES WHERE Variable_name = 'hostname';
SHOW VARIABLES WHERE Variable_name = 'port';
I had this same problem on AWS - and turns out that my security group was blocking the connection. I temporarily opened up all connections and voila! It connected!
Do you have any type of FW or host-based FW that could be blocking the connection? I thought it was my code and all was fine. Also check the port you are connecting on.
If you are using Docker, you might need to use host.docker.internal instead of localhost.
I managed to solve my issue by using the port without any quotation like so:
port = 3306,
You need to add the port to the connection as well. Try this and it works fine.
pymysql(Module Name).connect(host="localhost", user="root", passwd="root", port=8889, db="db_name")

python mysql connection problem

This code works fine:
import MySQLdb
db = MySQLdb.connect("localhost", "root", "","bullsorbit")
cursor = db.cursor()
cursor.execute("Select * from table where conditions'")
numrows = int(cursor.rowcount)
print 'Total number of Pages : %d ' % numrows
but if I give my IP address
db = MySQLdb.connect("192.168.*.*", "root", "","bullsorbit")
it will give this error
super(Connection, self).__init__(*args, **kwargs2)
_mysql_exceptions.OperationalError: (2003, "Can't connect to MySQL server on 'ip address' (111)")
Code 2003 is a standard MySQL client error:
Error: 2003 (CR_CONN_HOST_ERROR) Message: Can't connect to MySQL server on '%s' (%d)
I'd guess that your user is not allowed to connect to the MySQL server using an iP-address. What happens if you try a connection usign the MySQL commandline client?
$ mysql --host=192.168.1.1 -u root bullsorbit
with localhost you connect via loopback-interface.
with ip-addr you connect - as you connect from extern.
if your server allows only the local (loopback) connection
your ip-addr connection fails. (security!)
look at your mysql config, maybe only local-connections are allowed.
is the skip-networking switch off (in the mysql-conf) ?
#skip-networking
For the 2003 error, another possibility is that too many connections are being attempted in too short of time. I noticed this same behavior when I had 127.0.0.1 as my connect string. First I replaced it with localhost which got me further but still the same 2003 error. Then I saw that if I scaled back the number of calls the error disappeared completely.
Instead of:
db = MySQLdb.connect("192.168..", "root", "","bullsorbit")
try:
db = MySQLdb.connect(user="root", host="192.168..", db="bullsorbit")
Password will default to empty string and try the usual identity methods. Host will also default to localhost on default port.

Categories

Resources