I am logged into windows 10 where I am trying to run a connection to oracle db as:
import cx_Oracle
import pandas as pd
qry = 'select * from Table11 where rownum < 20'
conn = cx_Oracle.connect('uid', 'pwd', 'myDBOracle')
testData = pd.read_sql(qry, conn)
The username and password for the database myDBOracle is same as my windows authentication. However, windows authentication changes every month. So, I was wondering whether there was a way to recover the current authentication password for windows so that I don't have to worry about my query breaking every month after password change; since the windows authentication change flows to database also.
I am currently doing:
import os
conn = cx_Oracle.connect(os.getlogin(), 'pwd', 'myDBOracle')
If your DB user account was created with IDENTIFIED EXTERNALLY (see external authentication), then connect with:
import cx_Oracle
conn = cx_Oracle.connect(dsn = "the_tns_entry_name")
See cx_Oracle with Windows authentication
Related
I have implemented an application using python, PostgreSQL, pyqt5, Sqlalchemy and made an execution file for it through pyInstaller.
I tried installing this app on some laptops which had PostgreSQL 13 installed already on them. But there is a problem.
In some Laptops it's Ok and everything runs successfully and the database is created along with its tables on PostgreSQL, we can check it through Pgadmin 4 and we can work with the application successfully, but in some other laptops the database is created but not its tables and so the console stops and nothing appears and when we check Pgadmin there only is the database name not its tables.
P.S: the systems are Windows 10 and Windows 7.
I have no idea what to check or what to do I would appreciate it if anyone can give me any ideas.
the following code is base.py:
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy_utils import database_exists, create_database
from sqlalchemy import Column
engine = create_engine('postgresql://postgres:123#localhost:5432/db23')
if not database_exists(engine.url):
create_database(engine.url)
Session = sessionmaker(bind=engine)
Base = declarative_base()
and the following function is called in initializer function of the app:
def the_first_time_caller(self):
session = Session()
# 2 - generate database schema
Base.metadata.create_all(engine) # create tables in the database
session.commit()
session.close()
with Updating Python and downgrading Sqlalchemy, It runs successfully now.
I have trouble connecting to the Azure postgres database from python. I am following the guide here - https://learn.microsoft.com/cs-cz/azure/postgresql/connect-python
I have basically the same code for setting up the connection.
But the psycopg2 and SQLalchemy throw me the same error:
OperationalError: server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.
I am able to connect to the instance by other client tools like dbeaver but from python it does not work.
When I investigate in Postgres logs I can see that the server actually authorized the connection but the next line says
could not receive data from client: An existing connection was forcibly closed by the remote host.
Python is 3.7
psycopg's version is 2.8.5
Azure Postgres region is in West Europe
Does someone has any suggestion on what should I try to make it work?
Thank you!
EDIT:
The issue resolved itself. I tried the same setup a few days later and it started working. Might have been something wrong with the Azure West Europe.
I had this issue too. I think I read somewhere (I forget where) that Azure has an issue with the # you have to for the username (user#serverName).
I created variables and an f-string and then it worked OK.
import sqlalchemy
username = 'user#server_name'
password = 'PassWord!'
host = 'server_name.postgres.database.azure.com'
database = 'your_database'
conn_str = f'postgresql+psycopg2://{username}:{password}#{host}/{database}'
After that:
engine = sqlalchemy.create_engine(conn_str, pool_pre_ping=True)
conn = engine.connect()
Test it with a simple SQL statement.
sql = 'SELECT * FROM public.some_table;'
results = conn.engine.execute(sql)
This was a connection in UK South. Before that it did complain about the format of the username having to use #, although the username was correct, as tested from the command line with PSQL and another SQL client.
psql user was created as part of the following:
postgres=# create database testdb;
postgres=# create user testuser with encrypted password 'testpass';
postgres=# grant all privileges on database testdb to testuser;
postgres=# alter user testuser createdb;
The below python3 script functions if database "testdb" exists.
However the script fails:
(NameError: name 'con' is not defined)
if "testdb" does not exist.
I fail to understand the requirement, as I havent asked to connect to the db yet. any assistance you can offer to help me understand is appreciated in advance. tnx.
# import modules
import psycopg2
# connect to db server
try:
con = psycopg2.connect(
host = "127.0.0.1",
port = "5432",
user = "testuser",
password = "testpass")
except:
print("Unable to connect to db server")
# create cursor
cur = con.cursor()
# display list of db on server
cur.execute("""SELECT datname from pg_database""")
rows = cur.fetchall()
# print list of db on server
print ("\nConnection successful. Listing databases on server:\n")
for row in rows:
print (" ", row[0])
# close the cursor
print ("\nClosing server connection.\n")
cur.close()
# close the connection
con.close()
In PostgreSQL's libpq (which psycopg2 is based on), if you specify a user name but not a dbname, it automatically tries to connect to the database which takes the same spelling as the user you specified.
You specify the user 'testuser', but don't specify a database, so it tries to connect to the database spelled 'testuser'. If that doesn't exist, of course the connection will fail.
You said the database which has to exist for this to work is "testdb", but I see that at one point you had specified the user name as "testdb" but then edited your question and changed it to "testuser". So I think the example you show is not the code you actual are running, as you did some kind of piecemeal editing of it after the fact.
In your connection code, you should specify a dbname which you know already exists.
You should really look at the gevent connection I wrote over here. It automates all of this for you and you don't have to reinvent the wheel.
Python Postgres psycopg2 ThreadedConnectionPool exhausted
I am pretty much new to this concept.
Currently, I am connecting to oracle database directly using the credentials within a python script but I want to store the connection string in a text file or a separate .py file and call them as I use the same credentials for multiple scripts.
I am using cx_oracle and sqlalchemy packages to connect to two databases as I extract data from the source and push it to the target(both the source and target are oracle databases).
import cx_Oracle
from sqlalchemy import create_engine, types
dsn_tns = cx_Oracle.makedsn('shost', 'sport', service_name='sservice_name')
conn = cx_Oracle.connect(user='suser', password='spw', dsn = dsn_tns)
engine = create_engine('oracle://tuser:tpw#thost:tport/tservice_name')
I'd really want to automate this process as I reuse the same connection string in multiple scripts and I'd really appreciate if I can get some help.
I want to connect to MSSQL server2012 from Python using pyodbc on a Debian8 host. The current code already works for Azure SQL server but not for local SQL server.
The connection string looks like this:
import pyodbc
server = 'IP'
database = 'DB_Name'
username = 'user'
password = 'pass'
driver = '{ODBC Driver 17 for SQL Server}'
cnxn = pyodbc.connect('DRIVER='+driver+';SERVER='+server+';PORT=1433;DATABASE='+database+';UID='+username+';PWD='+ password)
I had to use IP address because I could not reach SQL server via name. I can connect to the server with SSMS on a windows machine. I have tried the following combinations as well:
server='sqlservername\instancename'
server='IP, port'
server='IP\instancename'
driver='SQL Server'
Integrated_Security=false;
Trusted_Connection=no;
but none of them worked. I got either Login timeout or error in registering user. I run the same python code on windows machine without any problem.
Finally i found the correct combination. Besides thanks to #GordThompson the TCP/IP was enabled but on another port.
import pyodbc
server = 'IP\InstanceName, port'
database = 'DB_Name'
username = 'user'
password = 'pass'
driver = '{ODBC Driver 17 for SQL Server}'
cnxn = pyodbc.connect('DRIVER='+driver+';SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)