I'm trying to create a postgres DB using a python script. Some research showed that using the psycopg2 module might be a way to do it. I installed it and made the required changes in the pg_hba.conf file. I used the following code to create the DB:
#!/usr/bin/python
# -*- coding: utf-8 -*-
from psycopg2 import connect
import sys
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
con = None
con = connect(user='****', host = 'localhost', password='****')
dbname = "voylla_production1710"
con.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
cur = con.cursor()
cur.execute('CREATE DATABASE ' + dbname)
cur.close()
con.close()
I tried replacing con = connect(user='nishant', host = 'localhost', password='everything') with con = connect(user='nishant', password='everything')
But I'm getting the following Error:
con = connect(user='nishant', host = 'localhost', password='everything')
File "/usr/lib/python2.7/dist-packages/psycopg2/__init__.py", line 179, in connect
connection_factory=connection_factory, async=async)
psycopg2.OperationalError: FATAL: database "nishant" does not exist
Could someone please tell me the right way of doing it.
Thanks
PostgreSQL's client connects to a database named after the user by default.
This is why you get the error FATAL: database "nishant" does not exist.
You can connect to the default system database postgres and then issue your query to create the new database.
con = connect(dbname='postgres', user='nishant', host='localhost', password='everything')
Make sure your nishant user has permission to create databases.
Edit: By the way, check out the ~/.pgpass file to store password securely and not in the source code (http://www.postgresql.org/docs/9.2/static/libpq-pgpass.html). libpq, the postgresql client librairy, check for this file to get proper login information. It's very very handy.
Related
I am using the community version of pycharm, my hope was to put the sensitive database connection credentials in a separate file in my pycharm project, so if I shared my other files that contain the actual code, they wouldn't have my connection info. Here is what the "connect1.py" file contains:
import psycopg2
# Database Credentials
DB_HOST = "localhost"
DB_NAME = "movie_watchlist1"
DB_USER = "postgres"
DB_PASS = "postgres123"
def database_credentials():
psycopg2.connect(dbname=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST)
pass
Here are the lines in my database.py file that tries to access this information:
import psycopg2
from connect1 import database_credentials
connection = psycopg2.connect(database_credentials())
And here is the error:
TypeError: missing dsn and no parameters
I think the problem is with the "connection = psycopg2.connect(database_credentials())" line, but I haven't been able to figure it out, any help or suggestions would be greatly appreciated.
import psycopg2
# Database Credentials
DB_HOST = "localhost"
DB_NAME = "movie_watchlist1"
DB_USER = "postgres"
DB_PASS = "postgres123"
def database_credentials():
return psycopg2.connect(dbname=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST)
from connect1 import database_credentials
connection = database_credentials()
I am having problems connecting to a remote Oracle DB using cx_Oracle in my python application.
I have tried a lot of different ways of configuring/formulating my connection string based on a lot of google searching etc but I seem to get the same error message almost each time no matter what I try.
My attempts looks like this:
import cx_Oracle
ip = '[IP ADDRESS]'
port = [PORT]
service_name = '[SERVICE NAME]'
dsn = cx_Oracle.makedsn(ip, port, service_name=service_name)
db = cx_Oracle.connect('[USERNAME]', '[PASSWORD], dsn)
Result: DatabaseError: ORA-12170: TNS:Connect timeout occurred
import cx_Oracle
conn_str = '[USERNAME]/[PASSWORD]#[HOST IP]/[SERVICE NAME]'
conn = cx_Oracle.connect(conn_str)
Result: DatabaseError: ORA-12170: TNS:Connect timeout occurred
import cx_Oracle
user= '[USERNAME]'
pwd = '[PASSWORD]'
host = '[HOST IP]'
service_name = '[SERVICE NAME]'
portno = '[PORT]'
conn = cx_Oracle.connect(user, pwd, '{}:{}/{}'.format(host,portno,service_name))
Result: DatabaseError: ORA-12170: TNS:Connect timeout occurred
import cx_Oracle
connstr = '[USERNAME]/[PASSWORD]#[SERVICE NAME]'
conn = cx_Oracle.connect(connstr)
Result: DatabaseError: ORA-12154: TNS:could not resolve the connect identifier specified
I have Toad installed on my PC and have no problems what so ever connecting to the DB with that.
Any ideas what could be the problem ?
Thanks in advance
I have this standard way to connect
import cx_Oracle
host="myserver"
port=myport
sid='myservicename'
user='myuser'
password='mypassword'
sid = cx_Oracle.makedsn(host, port, service_name=sid)
connection = cx_Oracle.connect(user, password, sid, encoding="UTF-8")
cursor = connection.cursor()
cursor.execute('select 1 from dual')
And it works without any issue. In your case, it is quite strange that you got a timeout, which normally indicates a network problem rather than a connection issue. If you are using cx_Oracle version 8, you don't need to specify the encoding as UTF-8 as it is the default one.
See how it works.
C:\python>type testconn.py
#from __future__ import print_function # needed for Python 2.7
import cx_Oracle
import os
host="myserver"
port=myport
sid='database_service_name'
user='myuser'
password='mypassword'
sid = cx_Oracle.makedsn(host, port, service_name=sid)
connection = cx_Oracle.connect(user, password, sid, encoding="UTF-8")
cursor = connection.cursor()
cursor.execute('select 1 from dual')
for row in cursor:
print(row)
C:\python>python testconn.py
(1,)
C:\python>
I am using mysql.connector to connect to a mysql DB, while i can connect manually to the db using sql server management, if i try connecting via code, it returns this error after awhile :
mysql.connector.errors.OperationalError: 2055: Lost connection to MySQL server at 'host:1234', system error: 10054 An existing connection was forcibly closed by the remote host
These are the connection details :
connection = mysql.connector.connect(host='host',
port = '1234',
database='DBname',
user='Usr',
password='pwd')
If I create a local mysql DB, the connection works just fine.
I assume some security stuff is going on, anyone else had encountered this situation ? Anything that I'm doing wrong? Should I add anything to the connection.connect input ?
Full code for reference :
import mysql.connector
from mysql.connector import Error
connection = mysql.connector.connect(host='host',
port = '1234',
database='DBname',
user='Usr',
password='pwd')
sql_select_Query = "select * from TableName"
cursor = connection.cursor()
cursor.execute(sql_select_Query)
records = cursor.fetchall()
print("Total numb of rows selected is : ", cursor.rowcount)
print("\nPrinting each row")
for row in records:
print(row)
connection.close()
I am not able to connect to MySQL sever using python it gives and error which says
MySQLdb._exceptions.OperationalError: (1130, "Host 'LAPTOP-0HDEGFV9' is not allowed to connect to this MySQL server")
The code I'm using:
import MySQLdb
db = MySQLdb.connect(host="LAPTOP-0HDEGFV9", # your host, usually localhost
user="root", # your username
passwd="abcd13de",
db="testing") # name of the data base
cur = db.cursor()
cur.execute("SELECT * Employee")
for row in cur.fetchall():
print(row[0])
db.close()
This is an authorization problem not a connectivity problem. Is the db running locally? If not, confirm with the admin where it is hosted. If so, try changing the host parameter to 127.0.0.1?
As described here the admin can get the hostname by running:
select ##hostname;
show variables where Variable_name like '%host%';
If the connection was timing out you could try setting the connect_timeout kwarg but that's already None by default.
I am unable to connected to database in linux using psycopg2. I have postgresql installed in linux and my code is:
import psycopg2
def testEgg():
conn = psycopg2.connect("dbname = myDatabase user = postgres port = 5432")
cur = conn.cursor()
cur.execute("CREATE TABLE egg ( num integer, data varchar);")
cur.execute("INSERT INTO egg values ( 1, 'A');")
conn.commit()
cur.execute("SELECT num from egg;")
row = cur.fetchone()
print row
cur.close()
conn.close()
testEgg()
And the I got the error:
psycopg2.OperationalError: FATAL: Ident authentication failed for user "postgres"
This code runs well in windows7 but got above mentioned error in linux.
Is there anything I need to do more in linux? Any suggestion will be appreciated.
Thank you.
It's not a problem due to your code, but due to the permission of the postgres user.
You should create a new user to access to your database and replace this :
conn = psycopg2.connect("dbname = myDatabase user = postgres port = 5432")
by (replace <your_user> by your real user name ...)
conn = psycopg2.connect("dbname = myDatabase user = <your_user> port = 5432")
To create a new user on postgres, you can use the 'createuser' binary. The documentation is available here.