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>
Related
PyODBC takes ~7 seconds to establish a connection with Azure SQL Server, is there a way to minimize this?
import os
import sys
import logging, logging.handlers
import getopt
import pyodbc
from database import *
# set up logging
logging.getLogger().setLevel(logging.INFO)
console = logging.StreamHandler()
console.setFormatter(logging.Formatter('%(asctime)s %(name)-12s %(levelname)s %(message)s'))
console.setLevel(logging.INFO)
logging.getLogger().addHandler(console)
logger = logging.getLogger("testapp")
def connect():
return pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)
def purgeStoreData(conn, div_id, purge_days, lookback_days, store_start, store_end):
store_list = get_store_list(conn, div_id, store_start, store_end)
cursor = conn.cursor()
for store in store_list:
logger.info("Store %s ...", store)
cursor.execute("some query")
if __name__ == "__main__":
try:
conn = connect()
purgeStoreData(conn, DIV_ID, PURGE_DAYS, LOOKBACK_DAYS, STORE_START, STORE_END)
logger.info("*** Completed succesfully")
finally:
conn.close()
Is there a way to display the network latency ?
Could you please try to connect using the ODBC Driver 17 for SQL Server? You may find this way faster.
import pyodbc
server = '<server>.database.windows.net'
database = '<database>'
username = '<username>'
password = '{<password>}'
driver= '{ODBC Driver 17 for SQL Server}'
with pyodbc.connect('DRIVER='+driver+';SERVER=tcp:'+server+';PORT=1433;DATABASE='+database+';UID='+username+';PWD='+ password) as conn:
with conn.cursor() as cursor:
cursor.execute("SELECT TOP 3 name, collation_name FROM sys.databases")
row = cursor.fetchone()
while row:
print (str(row[0]) + " " + str(row[1]))
row = cursor.fetchone()
Microsoft drivers for Python are here.
Please add the following to the connection string also: "Encrypt=yes;TrustServerCertificate=no;". When a client first attempts a connection to SQL Azure, it sends an initial connection request. Consider this a "pre-pre-connection" request. At this point the client does not know if SSL/Encryption is required and waits an answer from SQL Azure to determine if SSL is indeed required throughout the session (not just the login sequence, the entire connection session). A bit is set on the response indicating so. Then the client library disconnects and reconnects armed with this information.
When you set "Encrypt connection" to "yes" you avoid the "pre-pre-connection" and the connection is faster.
In addition, please verify latency on your internet connection.
I'm trying to connect to an oracle db using python through PyCharm, below is my code and a screenshot of the connection details
Code:
import cx_Oracle
try:
conn = cx_Oracle.connect('sys/123#//localhost:1521/XEPDB1')
except:
print("Connection Error")
exit()
Output
Connection Error
There are multiple ways to do that, either with SID or service name
SID :
import cx_Oracle
dsn_tns = cx_Oracle.makedsn('server', 'port', 'sid')
conn = cx_Oracle.connect(user='username', password='password', dsn=dsn_tns)
Service name :-
import cx_Oracle
dsn_tns = cx_Oracle.makedsn('server', 'port', service_name='service_name')
conn = cx_Oracle.connect(user='username', password='password', dsn=dsn_tns)
You can refer to this documentation HERE
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 attempting to connect to SQL Server Management Studio. My code is below and returns the error: "init() got an unexpected keyword argument 'trusted'." I am using pymysql, would like to connect using Windows Authentication, and am running on 64 bit windows machine. Any help would be appreciated.
Edit - removed trusted. Error I am now receiving is 'No connection could be made because the target machine actively refused it'
import pymysql
import pymysql.cursors
conn = pymysql.connect(host = 'DESKTOP-6CIMC97')
Have you checked out the example on GitHub? trusted doesn't seem to be required.
https://github.com/PyMySQL/PyMySQL/blob/master/example.py
#!/usr/bin/env python
from __future__ import print_function
import pymysql
conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='', db='mysql')
cur = conn.cursor()
cur.execute("SELECT Host,User FROM user")
print(cur.description)
print()
for row in cur:
print(row)
cur.close()
conn.close()
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.