Connection Error while connecting to PostgreSQL as postgres user? - python

I am not able connect to PostgreSQL remotely using python and psycopg2:
Here is my code.
>>> import psycopg2
>>> conn_string = "host='localhost' dbname='mydb' user='postgres'"
>>> print "Connecting to database\n ->%s" % (conn_string)
Connecting to database
->host='localhost' dbname='mydb' user='postgres'
>>> conn = psycopg2.connect(conn_string)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/tools/lib/python2.7/site-packages/psycopg2/__init__.py", line 164, in connect
conn = _connect(dsn, connection_factory=connection_factory, async=async)
psycopg2.OperationalError: could not connect to server: Connection refused
Is the server running on host "localhost" (::1) and accepting
TCP/IP connections on port 5432?
could not connect to server: Connection refused
Is the server running on host "localhost" (127.0.0.1) and accepting
TCP/IP connections on port 5432?
The password is not set for postgres user.
Generally, I can connect to database by running following method on host.
1. SSH to box
2. su - postgres
3. psql
4. \c mydb
The server runs PostgreSQL 9.1.

You're trying to connect to PostgreSQL on localhost using a script running on your computer, but there's no PostgreSQL server running there.
For this to work, you'd have to ssh to the remote server, then run your Python script there, where the PostgreSQL server is "local" relative to the Python script.
(That's why running psql works - because you're running it on the remote server, where PostgreSQL is "local" relative to psql).
Alternately, you could:
Use an SSH tunnel to forward the PostgreSQL port from the local computer to the remote one; or
Connect directly over TCP/IP to the remote PostgreSQL server using its host name or IP address, after enabling remote connections on the server.
Note that just putting the server's IP address or host name into the connection string instead of localhost will not work unless you also configure the server to accept remote connections. You must set listen_addresses to listen for non-local connections, add any required firewall rules, set pg_hba.conf to permit connections from remote machines, and preferably set up SSL. All this is covered in the Client Authentication chapter of the PostgreSQL user manual.
You'll probably find an SSH tunnel simpler and easier to understand.

Related

Does anyone know how to connect a PostgreSQL database to a Datalore notebook?

I'm working in Datalore (a jupyter notebook IDE) and I'm trying to connect to a postgresql (version 14) table via the following line of code.
df = pd.read_sql_table('emp','postgresql://{username}:{password}#localhost:5432/postgres')
where username and password are supplied in my notebook.
This gives the following error message:
OperationalError: (psycopg2.OperationalError) connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections? connection to server at "localhost" (::1), port 5432 failed: Cannot assign requested address Is the server running on that host and accepting TCP/IP connections? (Background on this error at: https://sqlalche.me/e/14/e3q8)
When trying to test the connection to my database from the Datalore side pane, I get the following error message:
Connection to localhost:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
I have already altered the IP address in pg_hba.conf from 127.0.0.0/32 to 0.0.0.0/0. Additionally, I have checked postgresql.conf and the listen_addresses = '*'.
My thoughts are that localhost shouldn't be used or that postmaster needs to be reset. If I am correct:
What should be used instead of localhost, and where do I find the correct hostname
How do I reset postmaster (I manually installed postgresql, I did not use Homebrew).
Is there anything else I haven't considered?

Connecting to PostgreSQL database through Python code

I have a Ubuntu virtual machine using Vagrant, I set it up and run it using vagrant up and vagrant ssh and I create the database psql -d dbname -f somesqlqueries.sql.
Whenever I try to connect to this database through python by doing conn = psycopg2.connect("dbname=dbname") I get this error:
psycopg2.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?
Looking at solutions for this issue I changed postgresql.conf to have listen_address = '*' and still the same error occurs.
Also tried to turn off the firewall and run sudo ufw allow 5432/tcp and the error still persistent.

Cannot connect to MySQL with MySQLdb in Python, can connect from command line

I'm having trouble connecting to my local MySQL database in python, but have no problem connecting from the command line.
When I try this:
db = MySQLdb.connect(host="localhost",
user="username",
passwd="password",
db="dbname",
port=3306,
unix_socket="/var/run/mysqld/mysqld.sock")
I get the following error:
OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)")
I get the same error when I don't explicitly pass in the socket path. I get a similar error when I use 127.0.0.1 instead of localhost as the host (also removing the unix socket argument):
OperationalError: (2003, "Can't connect to MySQL server on '127.0.0.1' (111)")
I know that MySQL is running, as when I can connect to the database from the command line no problem with mysql -u username -p dbname. I also know MySQL is listening on 127.0.0.1, when I run mysql -h 127.0.0.1 -p I can connect as well. I'm also sure it's listening on port 3306.

Connecting to Amazon rds with Python

Using MySQL Workbench, I can connect mysql running on amazon rds. I supply SSH Hostname, SSH Username, SSH Password, SSH Key File, MySQL Hostname, MySQL Server Port, Username, and Password.
However, I have a python script with which I'd like to connect to this same database. I tried using ssh tunneling:
with SSHTunnelForwarder(
(SSH Hostname, 22),
ssh_password=SSH Password,
ssh_username=SSH Username,
ssh_pkey= SSH Key File path,
remote_bind_address=(MySQL Hostname, MySQL Port) as server:
conn = MySQLdb.connect(
host = MySQL Hostname,
port = MySQL Port,
user = Username,
passwd = Password)
When I run the script, it hangs for about a minute, then says
'Can't connect to MySQL server on ~MySQL Hostname~'
I am unsure about the remote_bind_address. Since I don't supply that info when successfully connecting from MySQLWorkbench, is there a way to connect from Python without specifying remote_bind_address?
Additionally, I tried using the scripting tool in MySQL Workbench. I am able to load my python script, but then an error occurs at one of my imports, specifically 'import module requests'. The error indicates there is no module named requests. However, this module has been installed for a while, and I have imported and successfully used it outside of MySQL Workbench.

Heroku refuses connection to postgres database

I am trying to deploy my Flask app based on PostgreSQL on Heroku, but I when I try to create the table with db.create_all() I keep getting this error:
(psycopg2.OperationalError) could not connect t
rver: Connection refused
Is the server running on host "localhost" (127.0.0.1) and accepting
TCP/IP connections on port 5432?
Here is how my code looks like:
app=Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI']='postgres://kfgriimpfjecsv:Bk1*****G#localhost:5432/dd71doth8gopgh'
db=SQLAlchemy(app)
if __name__ == '__main__':
app.debug=True
app.run()
I am using Heroku Toolbelt to communicate with Heroku servers. Also, when I try this:
psql -p 5432 -h localhost
I get almost the same error:
psql: could not connect to server: Connection refused
Is the server running on host "localhost" (127.0.0.1) and accepting
TCP/IP connections on port 5432?
I also tried ec2-23-21-215-184.compute-1.amazonaws.com instead of localhost in the URI, but got the same error.
And here is the complete traceback that I get when I run db.create_all():
Any idea why the connection is being refused and how to solve this?
It seems I had to append a sslmode parameter to the database URI, so changing the second line to the following solved the problem:
app.config['SQLALCHEMY_DATABASE_URI']= "postgresql+psycopg2://kfgriimpfjecsv:Bk1*******G#ec2-23-21-215-184.compute-1.amazonaws.com:5432/dd71doth8gopgh?sslmode=require"

Categories