Unable to connect to remote sql servers using pypyodbc (Python) - python

I tried to use pypyodbc module to access remote MS SQL database 2014. However, when I run the below script, I got the error message saying:
Traceback (most recent call last):
File "C:\Users\username\Desktop\myscirpt.py", line 159, i
n <module>
db= pypyodbc.connect('DRIVER='+ driver + ';SERVER='+ client_db_ip +';PO
RT=' + port + ';DATABASE=' + database + ';trusted_connection=yes;')
File "C:\Python27\lib\site-packages\pypyodbc.py", line 2454, in __init__
self.connect(connectString, autocommit, ansi, timeout, unicode_results, read
only)
File "C:\Python27\lib\site-packages\pypyodbc.py", line 2507, in connect
check_success(self, ret)
File "C:\Python27\lib\site-packages\pypyodbc.py", line 1009, in check_success
ctrl_err(SQL_HANDLE_DBC, ODBC_obj.dbc_h, ret, ODBC_obj.ansi)
File "C:\Python27\lib\site-packages\pypyodbc.py", line 987, in ctrl_err
raise DatabaseError(state,err_text)
pypyodbc.DatabaseError: (u'08001', u'[08001] [Microsoft][SQL Server Native Clien
t 11.0]TCP Provider: An existing connection was forcibly closed by the remote ho
st.\r\n')
Below it's a very simple code for the db connection. The point here is that I can manually connect to the client db from the same machine, which is the one that my python script resides at. I'm curious what actually cause such issue?
driver = '{SQL Server Native Client 11.0}'
client_db_ip = 'client_db_ip' # client server ip
port = '1433'
database = 'UPG_TEST_MAIN'
db= pypyodbc.connect('DRIVER='+ driver + ';SERVER='+ client_db_ip +';PORT=' + port + ';DATABASE=' + database + ';trusted_connection=yes;')
print db
db.close()

Related

How to connect fdb database using Python in Ubuntu?

I am trying to connect fdb database using python. I am remotely connected to ubuntu. I have tried this:
path = '/home/ubuntu/Firebird4.0/A.fdb'
con = fdb.connect(host=host, database=path, user=user, password=pswd2, charset='UTF8')
and many combinations for the path of ubuntu fdb file. How can I solve this problem? Is it about the wrong host, port, password, or something?
I got this error all the time
Traceback (most recent call last):
File "/home/ubuntu/test.py", line 24, in <module>
conn = connection()
File "/home/ubuntu/test.py", line 15, in connection
con = fdb.connect(host=host, database=path, user=user, password=pswd2, charset='UTF8')
File "/home/ubuntu/.local/lib/python3.10/site-packages/fdb/fbcore.py", line 869, in connect
raise exception_from_status(DatabaseError, _isc_status,
fdb.fbcore.DatabaseError: ('Error while connecting to database:\n- SQLCODE: -902\n- Unable to complete network request to host "15.206.100.218".\n- Failed to establish a connection.', -902, 335544721)

Can't connect to MySQL server on 'localhost:3306' (10061) During handling of the above exception in python

i wrote a program to check if program can make connection to MySQL server and if cant connect to server print a error message and this is the program that i wrote
import mysql.connector
is_connected = False
def check_connection():
global is_connected
try:
db = mysql.connector.connect(
host="localhost",
user="root",
passwd=""
)
if db.is_connected():
print("Connected to MySQL database")
is_connected = True
except:
print("Unable to connect to MySQL database check if mysql server is running on defaul port which is 3306")
return is_connected
the whole objective here is print a error message when MySQL server is not running so i stop the server and run the file it works fine when in its own file but when it import to another file and call the check_cconnection method its give this error
Traceback (most recent call last):
File "C:\Users\thevi\AppData\Local\Programs\Python\Python310\lib\site-packages\mysql\connector\connection_cext.py", line 236, in _open_connection
self._cmysql.connect(**cnx_kwargs)
_mysql_connector.MySQLInterfaceError: Can't connect to MySQL server on 'localhost:3306' (10061)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "t:\Projects\Python_Projects\assignment\anatha.py", line 2, in <module>
from create_db import createDb
File "t:\Projects\Python_Projects\assignment\create_db.py", line 3, in <module>
db = mysql.connector.connect(
File "C:\Users\thevi\AppData\Local\Programs\Python\Python310\lib\site-packages\mysql\connector\__init__.py", line 272, in connect
return CMySQLConnection(*args, **kwargs)
File "C:\Users\thevi\AppData\Local\Programs\Python\Python310\lib\site-packages\mysql\connector\connection_cext.py", line 85, in __init__
self.connect(**kwargs)
File "C:\Users\thevi\AppData\Local\Programs\Python\Python310\lib\site-packages\mysql\connector\abstracts.py", line 1028, in connect
self._open_connection()
File "C:\Users\thevi\AppData\Local\Programs\Python\Python310\lib\site-packages\mysql\connector\connection_cext.py", line 241, in _open_connection
raise errors.get_mysql_exception(msg=exc.msg, errno=exc.errno,
mysql.connector.errors.DatabaseError: 2003 (HY000): Can't connect to MySQL server on 'localhost:3306' (10061)
how to ger rid of this error

Error connection to postgres database using psycopg2

I am trying to connect to a postgres database to run some queries for validation. Trying to establish connection via psycopg2. Have tried passing actual values for host instead of variables.
Tried the connection using psql to verify the connection parameters, password etc and they are right too.
But with the code below it always errors out with the below error
conn1 = psycopg2.connect(host=db_host,database=db_instance_name,user=masterusername,port=db_port,password=masterpassword)
cur1 = conn1.cursor()
print ('\n************Connection is successful ************ \n')
Traceback (most recent call last):
File "restored_db_details_draft.py", line 50, in <module>
conn_test = psycopg2.connect(host="***",database="my_db_name",user="master",port="9876",password="****")
File "/Users/me/Library/Python/3.8/lib/python/site-packages/psycopg2/__init__.py", line 127, in connect
conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.OperationalError: server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.

Python script to Connect to remote mongoDB using ssh-tunnel and pymongo client is failing with errors

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()

Trouble establishing connection to server with PyMySQL [WinError 10054]

Pretty new to both Python and SQL, so please excuse my noobishness. We have a server at my company that I'm trying to connect to through some python code. I have the correct IP address and logon credentials, and I can connect to it in SQL Server Management Studio without any issues, but I can't connect to it through PyCharm's database feature or through my code. I'm running python 3.6 if that makes a difference.
This is the code that I'm running (I've omitted the server ip address and logon credentials for security):
import pymysql
db = pymysql.connect(host='server ip',
port=1433,
user='username',
passwd='password',
db='Development DB')
cursor = db.cursor()
cursor.execute("SELECT VERSION()")
data = cursor.fetchone()
print("Database version : %s" % data)
db.close()
When I run the code, after about 2 minutes of nothing happening I get this error:
Traceback (most recent call last):
File "C:\Program Files\Python35\lib\site-packages\pymysql\connections.py", line 1021, in _read_bytes
data = self._rfile.read(num_bytes)
File "C:\Program Files\Python35\lib\socket.py", line 575, in readinto
return self._sock.recv_into(b)
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:/Users/aubrey_s/PycharmProjects/Drawings_Converter/Drawings_Converter.py", line 5, in <module>
db = pymysql.connect(host='ip address', port=1433, user='username', passwd='password', db='Development DB')
File "C:\Program Files\Python35\lib\site-packages\pymysql\__init__.py", line 90, in Connect
return Connection(*args, **kwargs)
File "C:\Program Files\Python35\lib\site-packages\pymysql\connections.py", line 706, in __init__
self.connect()
File "C:\Program Files\Python35\lib\site-packages\pymysql\connections.py", line 931, in connect
self._get_server_information()
File "C:\Program Files\Python35\lib\site-packages\pymysql\connections.py", line 1245, in _get_server_information
packet = self._read_packet()
File "C:\Program Files\Python35\lib\site-packages\pymysql\connections.py", line 987, in _read_packet
packet_header = self._read_bytes(4)
File "C:\Program Files\Python35\lib\site-packages\pymysql\connections.py", line 1029, in _read_bytes
"Lost connection to MySQL server during query (%s)" % (e,))
pymysql.err.OperationalError: (2013, 'Lost connection to MySQL server during query ([WinError 10054] An existing connection was forcibly closed by the remote host)')
From what I can understand, it looks like a connection was established, but the server forced it to close after a while. Can anyone offer me some more insight into what the problem might be? Thanks in advance!
As I wrote in another post, you may want to try using pymssql, in case your database is not a MySQL DB but a Microsoft SQL DB.

Categories