I am trying to connect to a remote Oracle database using Python.
I am able to access the database directly using DBeaver and I have copied the parameters in the Python code below from the "Connection Configuration --> Connection settings --> General" tab (which can be opened by right-clicking on the database and selecting "Edit connection"):
import cx_Oracle
host_name = # content of "Host"
port_number = # content of "Port"
user_name = # content of "User name"
pwd = # content of "Password"
service_name = # content of "Database" (the "Service Name" option is selected)
dsn_tns = cx_Oracle.makedsn(host_name, port_number, service_name = service_name)
conn = cx_Oracle.connect(user = user_name, password = pwd, dsn = dsn_tns)
However, I get the following error:
DatabaseError: ORA-12541: TNS:no listener
Other answers I found related to this question suggested modifying some values inside the listener.ora file, but I have no such file on my computer nor do I know where it can be retrieved. Does anyone have any suggestions?
There would be two reason for that error.
The database was briefly unavailable at the time when you tried to access
The Oracle client application on your machine is not configured correctly
I think thi config is not correct.
See the link : https://oracle.github.io/python-cx_Oracle/
ip = '192.168.1.1'
port = 1521
SID = 'YOURSIDHERE'
dsn_tns = cx_Oracle.makedsn(ip, port, SID)
db = cx_Oracle.connect('username', 'password', dsn_tns)
Related
I have my report dashboard that I'm developing using Django and I want to connect it to my MySQL database without using models.py or migrations.
Basically, here's what I've done so far.
views.py
import configparser
config = configparser.ConfigParser()
config.read('db.ini')
def getConnection():
host = config['ord']['host']
port = config['ord']['port']
database = config['ord']['database']
password = config['ord']['password']
user = config['ord']['user']
connection = pymssql.connect(host=host, user=user, password=password, database=database)
cursor = connection.cursor()
print("Connection Succesfull")
return cursor
def fill_weight(request):
try:
sql = u """
SELECT * FROM fill_weight;
"""
sql =sql.encode('utf-8')
cursor.execute(sql)
cursor.fetchall()
db.ini
[oof_ord]
host = localhost
port = 3306
database = xxxxxxxxxxx
user = xxxxxxxxxxx
password = xxxxxxxxxxx
default-character-set = utf8
The reason why I want to do this is because I don't have the official database that I'm going to use for this system and I want to easily access it by putting it's database credentials to my db.ini and access it to show the data without doing any migrations.
Is there anyone that can help me ?
I want to get the column names in redshift using python boto3
Creaed Redshift Cluster
Insert Data into it
Configured Secrets Manager
Configure SageMaker Notebook
Open the Jupyter Notebook wrote the below code
import boto3
import time
client = boto3.client('redshift-data')
response = client.execute_statement(ClusterIdentifier = "test", Database= "dev", SecretArn= "{SECRET-ARN}",Sql= "SELECT `COLUMN_NAME` FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA`='dev' AND `TABLE_NAME`='dojoredshift'")
I got the response but there is no table schema inside it
Below is the code i used to connect I am getting timed out
import psycopg2
HOST = 'xx.xx.xx.xx'
PORT = 5439
USER = 'aswuser'
PASSWORD = 'Password1!'
DATABASE = 'dev'
def db_connection():
conn = psycopg2.connect(host=HOST,port=PORT,user=USER,password=PASSWORD,database=DATABASE)
return conn
How to get the ip address go to https://ipinfo.info/html/ip_checker.php
pass your hostname of redshiftcluster xx.xx.us-east-1.redshift.amazonaws.com or you can see in cluster page itself
I got the error while running above code
OperationalError: could not connect to server: Connection timed out
Is the server running on host "x.xx.xx..xx" and accepting
TCP/IP connections on port 5439?
I fixed with the code, and add the above the rules
import boto3
import psycopg2
# Credentials can be set using different methodologies. For this test,
# I ran from my local machine which I used cli command "aws configure"
# to set my Access key and secret access key
client = boto3.client(service_name='redshift',
region_name='us-east-1')
#
#Using boto3 to get the Database password instead of hardcoding it in the code
#
cluster_creds = client.get_cluster_credentials(
DbUser='awsuser',
DbName='dev',
ClusterIdentifier='redshift-cluster-1',
AutoCreate=False)
try:
# Database connection below that uses the DbPassword that boto3 returned
conn = psycopg2.connect(
host = 'redshift-cluster-1.cvlywrhztirh.us-east-1.redshift.amazonaws.com',
port = '5439',
user = cluster_creds['DbUser'],
password = cluster_creds['DbPassword'],
database = 'dev'
)
# Verifies that the connection worked
cursor = conn.cursor()
cursor.execute("SELECT VERSION()")
results = cursor.fetchone()
ver = results[0]
if (ver is None):
print("Could not find version")
else:
print("The version is " + ver)
except:
logger.exception('Failed to open database connection.')
print("Failed")
I'm using jaydebeapi to connect to an oracle DB. The code is as follows:
host = [address]
port = "1521"
sid = "ctginst1"
database = "oracle"
drivertype = "thin"
uid = [user]
pwd = [pass]
driver_class = "oracle.jdbc.OracleDriver"
driver_file = "ojdbc10.jar"
connection_string="jdbc:{}:{}#{}:{}:{}".format(database, drivertype, host, port, sid)
conn=jaydebeapi.connect(driver_class, connection_string, [uid, pwd], driver_file, )
However this fails and gives me an error:
java.lang.RuntimeException: Class oracle.jdbc.OracleDriver not found
Edit:
By passing CLASSPATH with the .jar's location when starting JVM and only then attempting the connection I managed to proceed further with
import jpype
jpype.startJVM(jpype.getDefaultJVMPath(), '-Djava.class.path=%s' % driver_file)
And now I am getting java.sql.SQLException: Invalid Oracle URL specified error
Okay so from there there was apparently a colon missing before the "#".
The full successful connection code looks like:
import jaydebeapi
import jpype
host = host
port = "1521"
sid = "ctginst1"
database = "oracle"
drivertype = "thin"
uid = user
pwd = password
driver_class = "oracle.jdbc.OracleDriver"
driver_file = "C:\ojdbc8.jar"
connection_string="jdbc:{}:{}:#{}:{}:{}".format(database, drivertype, host, port, sid)
jpype.startJVM(jpype.getDefaultJVMPath(), '-Djava.class.path=%s' % driver_file)
conn=jaydebeapi.connect(driver_class, connection_string, [uid, pwd])
I'm using MySQLdb for python, and I would like to connect to a database hosted on an other PC on the same network/LAN.
I tried the followings for host:
192.168.5.37
192.168.5.37:3306
http://192.168.5.37
http://192.168.5.37:3306
None of the above work, I always get the
2005, Unknown MySQL server host ... (0)
What might be the problem?
Code:
db = MySQLdb.connect(host="192.168.5.37", user = "root" passwd = "password", db = "test1")
You can use MySQL Connector/Python, a standardized database driver for Python.
You must provide username, password, host, database name.
import mysql.connector
conn = mysql.connector.connect(user=username, password=password,
host="192.168.5.37",
database=databaseName)
conn.close()
You can download it from: https://dev.mysql.com/downloads/connector/python/
The IP you posted are local IPs
Give it a try with your external IP (for example on this website)
https://www.whatismyip.com/
If it works with the external IP, then it's maybe a misconfiguration of your firewall.
I have a .ini (configuration file) where I have mentioned the server name, Database Name, UserName and Password with which I can connect my app to the MSSQL
self.db = pyodbc.connect(
'driver={SQL Server};server=homeserver;database=testdb;uid=home;pwd=1234')`
corresponding data mentioned above connect statement is now in config.ini
self.configwrite = ConfigParser.RawConfigParser()
configread = SafeConfigParser()
configread.read('config.ini')
driver = configread.get('DataBase Settings','Driver')
server = str(configread.get('DataBase Settings','Server'))
db = str(configread.get('DataBase Settings','Database'))
user = str(configread.get('DataBase Settings','Username'))
password = str(configread.get('DataBase Settings','Password'))'
How can I pass these variables in the pyodbc connect statement?
I tried this:
self.db = pyodbc.connect('driver={Driver};server=server;database=db;uid=user;pwd=password')
But I am getting an error.
Other options for the connect function:
# using keywords for SQL Server authentication
self.db = pyodbc.connect(driver=driver, server=server, database=db,
user=user, password=password)
# using keywords for Windows authentication
self.db = pyodbc.connect(driver=driver, server=server, database=db,
trusted_connection='yes')
self.db = pyodbc.connect('driver={%s};server=%s;database=%s;uid=%s;pwd=%s' % ( driver, server, db, user, password ) )
%s is used to include variables into the string
the variables are placed into the string according to their order after the %
Mixing strings and input variable in sql connection string using pyodbc library - Python
inspired of this answer
`conn=pyodbc.connect('Driver={SQL Server};'
'Server='+servername+';'
'Database=master;'
'UID=sa;'
'PWD='+pasword+';'
)`