Connecting to oracle DB through python - python

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

Related

2003 (HY000): Can't connect to MySQL server on '***.database.windows.net:3306' (10060)

I am trying to connect Azure SQL database using mysql-connector-python library.
But I am getting above mentioned error.
Here I am attaching my code for reference.
I have been given access to my IP in the firewall.
import mysql.connector
from mysql.connector import errorcode
# Obtain connection string information from the portal
# Construct connection string
config = {
'host':'db.database.windows.net',
'user':'server#db',
'password':'********',
'database':'db',
'client_flags': [mysql.connector.ClientFlag.SSL],
'ssl_ca': 'DigiCertGlobalRootG2.crt.pem'
}
try:
conn = mysql.connector.connect(**config)
print("Connection established")
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Something is wrong with the user name or password")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database does not exist")
else:
print(err)
else:
cursor = conn.cursor()
You cannot use the MySQL connector to connect to an Azure SQL database. There's a difference between a MySQL database and an Azure SQL database.
Azure SQL IS NOT MySQL
You can either use Azure Database for MySQL as a database, or check out this example on how to Use Python to query a SQL database, which uses an ODBC driver. As you can see in the linked article, they exist for macOS, Ubuntu and Windows.
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()

Connecting to remote Oracle DB using cx_Oracle

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>

Connect to MySQL via SSH Tunnelling | MySQL Connection not available

I am using the following python snippet to connect my MySQL database on a shared hosting server.
import mysql.connector
import sshtunnel
with sshtunnel.SSHTunnelForwarder(
('server.web-hosting.com', 21098),
ssh_username = 'ssh_username',
ssh_password = 'ssh_pass!23',
remote_bind_address = ('127.0.0.1', 3306)
) as tunnel:
connection = mysql.connector.MySQLConnection(
user = 'db_user',
password = 'db_pass',
host = '127.0.0.1',
port = tunnel.local_bind_port,
database = 'demo',
)
mycursor = connection.cursor()
query = "SELECT * FROM sample_table"
mycursor.execute(query)
I am getting the following error. I am able to connect to the database using DBeaver though.
MySQL Connection not available.

Connect to MySql DB using mysql.connector

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

Pymysql Windows Authentication Error

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

Categories