mssql python Connection - python

I am using Pycharm and try to link to a mssql server. When I link to a server that requires SQL authentication, the connect is created successfully. However, when I try to link to a server that requires my Windows Authentication, even though I use my username or password of windows log in, I cannot connect successfully. May I know what should be a proper way to setup if it is windows authentication.
I am using the below code:
import pymssql
conn=pymssql.connect(host="10.xx.xx.xx",user="CORPORATE/mywindowsloginname",password="mypassword",database="BIC_reference")
cur=conn.cursor()y
cur.execute('SELECT top 10 * FROM dbo.hi_invoiceline')
print (cur.fetchall())

in order to use Windows Authentication you have to add the property trusted_connection='yes' to your connection string. In this case you can omit user and password:
conn=pymssql.connect(host="10.xx.xx.xx",database="BIC_reference",trusted_connection='yes')

When using Windows Authentication, you should not specify any user credentials. The following should work assuming your Windows account has the relevant permissions:
conn=pymssql.connect(host="10.xx.xx.xx",database="BIC_reference")
I have tested this using pymssql-2.1.3. Using this version there was no need to specify trusted_connection='yes' (see apomene's answer), however, you may want to try that as well in case the above snippet doesn't work.

Related

can you use connectorx with SQL SERVER?

I am trying to reduce the loading times to extract a database from SQL SERVER. I have read a lot about this library but no matter how hard I have tried I have not been able to connect, can someone tell me if this is possible or guide me to configure it, thanks.
try using pyodbc config
per this discussion, at least some support has been added
I used sqlalchemy's urlib to make urls: and since url objects do not have a split() method, I cast to string.
connection_url = str(sqlalchemy.engine.URL.create("mssql",database=database, host=servername,
username=username,
password=password,
query = {'driver':'SQL Server'}))
I then used connectorx.read_sql(connection_url, 'select * from sys.databases') to validate the connection worked.
It worked for my system's sql server authentication database connections but failed to login for Windows Domain Authentication.

Connect to Snowflake via Python Connector OKTA

Anyone use the Python Connector to connect to Snowflake, specifically using https://<your_okta_account_name>.okta.com (i.e. the URL endpoint for Okta) to authenticate through native Okta.? I keep getting the error below, but I know it is the correct password/username. I am able to login fine via 'external browser" (but not through cloud9, nor do I want to continue this way)
Failed to connect to DB: appfolio.snowflakecomputing.com:443. Incorrect username or password was specified.
I have the following variables set up and I know I have correct password/username so going a little crazy , anyone here have this issue?
authenticator = 'https://company.okta.com'
user='user.name#company.com',
password= "password",
account='company'
People are having the same error (with & without MFA) but no solution was posted on snowflakes community board: https://community.snowflake.com/s/question/0D50Z00009JJKZGSA5/unable-to-connect-to-snowflake-using-aws-lambda

cx_Oracle giving ORA-01031 Insufficient privileges Logging in as SYSDBA

I am trying to connect Oracle remote database server using Python cx_Oracle. In sqlplus I do use "sqlplus / as sysdba" for connecting server using putty Console and i am to login successfully. Can you please help me on this why it was throwing this error.
import cx_Oracle
tns= cx_Oracle.makedsn('ip', port, SERVICE NAME = 'SID')
db = cx_Oracle.connect('SYS', 'password', tns, mode=cx_Oracle.SYSDBA)
It was throwing Error :
cx_Oracle Database Error ORA-01031: insufficient privileges
I already made one normal DB user and tried connecting with and it was Successful.
db = cx_Oracle.connect('USERNAME', 'password', tns)
You should be able to do most (all?) of the kind of things you mentioned with the normal "DBA" role. SYSDBA is often only necessary when doing things that require restart of the database, software and patch installation, or with backup/recovery scenarios, and is insanely overpowered for day-to-day uses. Depending on your version of Oracle, it is capable of bypassing many security features entirely, and is generally not safe to use within most scripts and applications for that reason. Use should be limited to things that only SYSDBA can do.
Additionally, the SYS user may not be allowed to connect over the network (you're using a TNS connection), as it is authenticated by the server operating system which implies local login only. That's why "sqlplus / as sysdba" works when you're logged in to the database server.
Consider the following:
If you must have actual SYSDBA privileges and nothing else will do, grant the SYSDBA role to another user and use that instead. As #Littlefoot suggested, never use the SYS or SYSTEM accounts for day-to-day administrative work, either on the server or remotely.
Never embed username and password in your scripts or application code, especially for an account that powerful. Use an Oracle Wallet to hold encrypted user credentials instead, or better yet prompt the user to enter them at runtime. Putting credentials like that directly in a script is a sure way to fail a security audit.
Follow the principle of least privilege and don't use a SYSDBA or DBA-role enabled account for anything else other than what you need those specific privileges to do (adding files, etc.). Use lesser accounts where possible.
When using privileged accounts like those with DBA or SYSDBA privileges over the network, you should encrypt all communications.
See these links for details:
https://pmdba.wordpress.com/2020/01/13/how-to-hide-oracle-passwords-in-a-script/
https://pmdba.wordpress.com/2014/10/16/database-account-password-storage/

Connect to SAP HANA by using HDODBC driver without UID and PWD in code

I am trying to connect to SAP HANA data source via Python code.
I did manage to establish a connection. I have a raw data string in my code as follows:
db = pyodbc.connect(driver = '{HDBODBC}', UID='username', PWD='password', SERVERNODE='server:<port_no>')
However, I do not want the UID and PWD fields in my string.
I did set up a DSN connection using the ODBC manager on Windows. But, I still need to enter my username and pwd as follows:
db = pyodbc.connect(DSN="MyDSN", UID='username', PWD='password')
How can I set up a connection without my UID and PWD being displayed in the python code?
I have been looking for the same option to use hdbuserstore key to be used with python for connecting to SAP HANA. Looks like HDB client hdbcli has that option added now.
The user that is running the script needs to have the PYTHON_PATH set to the location of the hdbclient or in the script you can have the path set.
from hdbcli import dbapi
conn = dbapi.connect(key='hdbuserstore key',CONNECTTIMEOUT=5)
conn.isconnected() will return True if the connection is successful.
hope this is helpful for someone!
Be carefull with parameter CONNECTTIMEOUT=5.
from hdbcli import dbapi
conn = dbapi.connect(key='hdbuserstore key',CONNECTTIMEOUT=5)
This means NOT 5 second because it is in ms. Toke me long time to find out this problem.
connectTimeout, Timeout in milliseconds
0 (use system's TCP/IP socket connection timeout)
Aborts connection attempts after the specified timeout.
for example create file in a secure place and load connection setting (UID, PWD encrypted password (heshkod)) from this file
This requirement is relatively easy to fulfill.
The SAP HANA client software (the package that also contains the ODBC driver) provides a program to set up a secure store for logon data: hdbuserstore.
In my blog I explained how that works in detail.
The core steps are
create the hdbuserstore entries for the operating system user that should use the application.
Syntax: hdbuserstore SET <KEY> <ENV> <USERNAME> <PASSWORD>
Example: hdbuserstore SET millerj "localhost:30115" JohnMiller 2wsx$RFV
The hdbuserstore key needs to be referred to in the ODBC connection.
To do that, fill the SERVERNODE parameter with #<KEYNAME> instead of the actual server address.
For the example above, the value would be #millerj.
And that's really all. The ODBC driver will try to look up the hdbuserstore entry provided upon connection and use that to connect to the database.
Check the documentation for more information on this.

SQLalchemy - Login with SQL server authentication

I am using SQLalchemy with pyodbc to connect to a SQL server. I can connect using "Windows Authentication":
create_engine('mssql+pyodbc://[ServerName]/[DatabaseName]',echo=True)
That is fine but when I try to login (SQL server authentication) it fails:
create_engine('mssql+pyodbc://[User]:{Password]#[ServerName]/[DatabaseName]',echo=True)
Is my code correct? Am I missing a setting?
Is there a way of listing database users to check the names?
Yes, your connection string is correct. Make sure the user/pwd combinations are correct. Also note that user/pwd can only be used for users which use "SQL Server authentication" (in the code below SQL_LOGIN) and not "Windows authentication"
Given you connect with enough permissions, you can execute the following to see all logins:
for x in session.execute("SELECT name, type, type_desc FROM sys.server_principals"):
print x

Categories

Resources