Unable to perform windows authentication for SQL Server using python - sql-server

My Python code shown below is written to create a SQL Server connection using Windows authentication. I have constraints to use adodbapi library for database connectivity.
Please can anyone tell me what is missing from this code? I referred to the library's documentation, but there is nothing mentioning Windows authentication.
I referred to a lot of articles about that exception. But they seems there's no help to understand the nature of exception and its resolution.
Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done.
Code:
import configparser
import adodbapi
config = configparser.ConfigParser()
config.read("C:/plugin/configsql.ini")
_SERVER_NAME = config['SQL']['SERVER_NAME']
_DATABASE = config['SQL']['DATABASE']
conn = adodbapi.connect("PROVIDER=MSOLEDBSQL;Data Source={0};Database={1};Integrated Security = True;".format(_SERVER_NAME,_DATABASE))
print(conn)
Exception:
Traceback (most recent call last):
File "C:\Arelle-master\venv1\lib\site-packages\adodbapi\adodbapi.py", line 113, in connect
co.connect(kwargs)
File "C:\Arelle-master\venv1\lib\site-packages\adodbapi\adodbapi.py", line 275, in connect
self.connector.Open() # Open the ADO connection
File "", line 3, in Open
File "C:\Arelle-master\venv1\lib\site-packages\win32com\client\dynamic.py", line 287, in ApplyTypes
result = self.oleobj.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes) + args)
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Provider', 'Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done.', None, 1240640, -2147217887), None)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "winAuthentication.py", line 8, in
conn = adodbapi.connect("PROVIDER=MSOLEDBSQL;Data Source={0};Database={1};Integrated Security = True;".format(_SERVER_NAME,_DATABASE))
File "C:\Arelle-master\venv1\lib\site-packages\adodbapi\adodbapi.py", line 117, in connect
raise api.OperationalError(e, message)
adodbapi.apibase.OperationalError: (com_error(-2147352567, 'Exception occurred.', (0, 'Provider', 'Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done.', None, 1240640, -2147217887), None), 'Error opening connection to "PROVIDER=MSOLEDBSQL;Data Source=MSSQLSERVER01;Database=TESTDB;Integrated Security = True;"')

Have you tried Trusted_Connection=yes? Here is my connection string that uses windows authentication (using pyodbc) but should be the same connection parameter, not Integrated Security.
conn = pyodbc.connect('Driver={SQL Server};'
'Server=ServerName;'
'Database=DatabaseName;'
'Trusted_Connection=yes;')
Or perhaps Integrated Security = SSPI, found mentioned here http://adodbapi.sourceforge.net/quick_reference.pdf
'Integrated Security=SSPI'

Related

Unable to connect to Pokertracker postgreSQL database

I am following this tutorial to connect to a PostgreSQL database stored on my computer.
I am using Windows 10 and I have installed PostgreSQL 9.3
I run the following code:
import psycopg2
class PostgreSQL():
def __init__(self):
self.conecta()
def conecta(self):
#establishing the connection
conn = psycopg2.connect(
database="PokerTracker 4 Database", user='postgres', password='dbpass', host='localhost', port= '5432')
#Creating a cursor object using the cursor() method
cursor = conn.cursor()
#Executing an MYSQL function using the execute() method
cursor.execute("select version()")
# Fetch a single row using fetchone() method.
data = cursor.fetchone()
print("Connection established to: ",data)
conn.close()
if __name__=='__main__':
PostgreSQL()
I receive the following error from the cmd while running the script:
C:\Users\USUARIO\Desktop\OMAHA>python postgresql.py
Traceback (most recent call last):
File "C:\Users\USUARIO\Desktop\OMAHA\postgresql.py", line 18, in <module>
PostgreSQL()
File "C:\Users\USUARIO\Desktop\OMAHA\postgresql.py", line 4, in __init__
self.conecta()
File "C:\Users\USUARIO\Desktop\OMAHA\postgresql.py", line 7, in conecta
conn = psycopg2.connect(
File "C:\Users\USUARIO\AppData\Local\Programs\Python\Python39\lib\site-packages\psycopg2\__init__.py", line 127, in connect
conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.OperationalError
What am I doing wrong? I copied the code from the tutorial.
If someone is trying to connect to Pokertracker database, the error was the database name was uncorrect. Go on pokertracker to File->Open User Data Folder. Open config folder, open pokertracker.cfg and there you have all the info.
In my case this are the parameters:
import psycopg2
class PostgreSQL():
def __init__(self):
self.conecta()
def conecta(self):
hostname = 'localhost'
username = 'postgres'
password = 'dbpass'
database = 'PT4DB'
myConnection = psycopg2.connect( host=hostname, user=username, password=password, dbname=database )
cursor = myConnection.cursor()
cursor.execute("""SELECT table_name FROM information_schema.tables
WHERE table_schema = 'public'""")
for table in cursor.fetchall():
print(table)
myConnection.close()
if __name__=='__main__':
PostgreSQL()
There you have the notes table. You can't edit the notes, they are protected by the system of Pokertracker. cheers

How to connect to Local MS SQL Express Edition using Python 3

I am trying to connect to local MS SQL Express Edition. I am using canopy for Python editing.
Code:
import pymssql
conn = pymssql.connect(server='******\SQLEXPRESS',user = 'MEA\*****',password='*****',database='BSEG')
cursor = conn.cursor()
cursor.execute('SELECT * FROM Table')
print(cursor.fetchone())
conn.close()
Error::
pymssql.pyx in pymssql.connect (pymssql.c:10734)()
_mssql.pyx in _mssql.connect (_mssql.c:21821)()
_mssql.pyx in _mssql.MSSQLConnection.init (_mssql.c:5917)()
ValueError: too many values to unpack (expected 2)
user = 'MEA\*****',password='*****'
MEA\***** seems to be Windows login, in this case you shouldn't pass in any password, your user name is enough, but you also should use Integrated security or Trusted parameter in your connection string
It should be smth like this:
server='******\SQLEXPRESS',Trusted_Connection=yes,database='BSEG'

Cannot connect to Redshift database with a driver even though play.ap.db.DB can do this for the same driver

I am trying to connect to a redshift server and run some sql commands. Here is the code that I have written:
Class.forName("org.postgresql.Driver")
val url: String = s"jdbc:postgres://${user}:${password}#${host}:${port}/${database}"
val connection: Connection = DriverManager.getConnection(url, user, password)
val statement = connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)
val setSearchPathQuery: String = s"set search_path to '${schema}';"
statement.execute(setSearchPathQuery)
But I am getting the following error:
java.sql.SQLException: No suitable driver found for jdbc:postgres://user:password#host:port/database
But when I am using play framework's default database library with the same configuration, then I am able to connect to database successfully. Below is the configuration for the default database:
db.default.driver=org.postgresql.Driver
db.default.url="postgres://username:password#hostname:port/database"
db.default.host="hostname"
db.default.port="port"
db.default.dbname = "database"
db.default.user = "username"
db.default.password = "password"
The problem was with the url. The correct format for the url is:
jdbc:postgresql://hostname:port/database

Getting error "Data provider could not be initialized" while connecting to backend

I have made an application in VB6 ( sybase 11 as backend ).
Now when i am trying to login on user machine it is giving me below errror :
"Data provider could not be initialized."
I AM USING BELOW CODE TO CONNECT TO BACKEND :
'/***** Procedure to establish connection to the back-end
On Error Resume Next
If pCon.State = 1 Then pCon.Close
pCon.Errors.Clear
pDSN = "TESTDSN"
pDatabase = "TESDB"
pCon.Open "Provider=MSDataShape;ODBC;Database=" & Trim(pDatabase) & ";UID="&
Trim( pUID) & ";PWD=" & pPWD & ";DSN=" & Trim(pDSN)
If pCon.Errors.Count > 0 Then
interr = 0
Do Until interr = pCon.Errors.Count
MsgBox pCon.Errors.Item(interr).Description
interr = interr + 1
Loop
fnCon = False
Else
fnCon = True
End If
Thanks.
You need a connection string that defines both the Provider and the Data Provider:
Provider=MSDataShape;Data Provider=providername
OLEDB is not ODBC. If you insist on using an ODBC driver (or DSN, which is an old ODBC construct) you will have to specify the "thunk into ODBC" Provider named MSDASQL as your Data Provider.
People often use a shortcut syntax for connection strings that implies this "adapter" Provider. That won't work here.
As far as I know even Sybase offers a proper OLEDB Provider though. I have no idea why people insist on using ODBC and DSNs today (DSNs were replaced by UDLs a long time ago) unless they cannot obtain a proper Provider.

TSQL - Executing CLR Permission

I got a sql procedure from a CLR (.net Assembly) that when executed returns an error
Msg 6522, Level 16, State 1, Procedure sp_HelloWorld, Line 0
A .NET Framework error occurred during execution of user defined routine or aggregate 'sp_HelloWorld':
System.Security.SecurityException: Request for the permission of type 'System.Data.SqlClient.SqlClientPermission, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
System.Security.SecurityException:
at System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet)
at System.Security.PermissionSet.Demand()
at System.Data.Common.DbConnectionOptions.DemandPermission()
at System.Data.SqlClient.SqlConnection.PermissionDemand()
at System.Data.SqlClient.SqlConnectionFactory.PermissionDemand(DbConnection outerConnection)
at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
at System.Data.SqlClient.SqlConnection.Open()
at HelloWorld.SQLCLR.HelloWorld()
This is my SQL script
go
drop procedure HelloWorld
drop assembly HelloWorld
GO
create assembly HelloWorld from 'F:\HelloWorld.dll'
with permission_set = safe
Go
create procedure sp_HelloWorld
as external name HelloWorld.[HelloWorld.SQLCLR].HelloWorld
go
exec sp_HelloWorld
and this is my Class (Assembly)
using Microsoft.SqlServer.Server;
using System.Data.SqlTypes;
using System.Data.SqlClient;
using System.Security.Permissions;
using System.Data;
namespace HelloWorld
{
public class SQLCLR
{
[Microsoft.SqlServer.Server.SqlProcedure]
public static void HelloWorld()
{
string connectString1 = #"Data Source=localhost;Initial Catalog=ItemData;Integrated Security=True";
SqlClientPermission permission = new SqlClientPermission(PermissionState.None);
permission.Add(connectString1, "", KeyRestrictionBehavior.AllowOnly);
permission.PermitOnly();
SqlConnection sqlcon = new SqlConnection(connectString1);
sqlcon.Open();
SqlCommand sqlcmd = new SqlCommand("SELECT Top 1 * FROM ItemData.dbo.Item", sqlcon);
SqlDataReader reader = sqlcmd.ExecuteReader();
SqlContext.Pipe.Send(reader);
sqlcon.Close();
}
}
}
The problem is simply that you are attempting to access an external resource in an Assembly that is marked as SAFE. Accessing external resources requires setting the Assembly to at least EXTERNAL_ACCESS (and in some cases UNSAFE). However, looking at your code, you are simply trying to connect to the local instance, and in that case there is a far easier (and faster) means of doing this: using "Context Connection = true;" as the ConnectionString.
The Context Connection is a direct connection to the current process / session, and it is sometimes referred to as the in-process connection. The benefits of using the Context Connection are:
can be done in Assemblies marked as SAFE
access to local temporary objects (temp tables and temp procedures, both with names starting with a single # instead of double ##)
access to SET CONTEXT_INFO and CONTEXT_INFO()
no connection startup overhead
Also:
whether you use the in-process, Context Connection or a regular / external connection, you do not need to formally request permission using SqlClientPermission
you should always clean up external resources by calling their Dispose() method. Not all objects have this, but SqlConnection, SqlCommand, and SqlDataReader certainly do. It is typical for people to wrap disposable objects in a using() block as it is a compiler macro that expands to a try / finally structure that calls the Dispose() method in the finally to ensure that it is called, even if an error occurs.
The Dispose() method of many / most disposable objects automatically handles the call to Close() so you usually do not need to call Close() explicitly.
Your code should look as follows:
[Microsoft.SqlServer.Server.SqlProcedure]
public static void HelloWorld()
{
using (SqlConnection sqlcon = new SqlConnection("Context Connection = true;")
{
using (SqlCommand sqlcmd = new SqlCommand("SELECT Top 1 * FROM ItemData.dbo.Item",
sqlcon))
{
sqlcon.Open();
using (SqlDataReader reader = sqlcmd.ExecuteReader())
{
SqlContext.Pipe.Send(reader);
}
}
}
}
I just wanted to add my two sense to this. I'm doing something very similiar and I'm getting the same error. Here is what I found, however b/c I don't have this level of access to the DB I can't test it.
Easiest( although not MSDN recommended just to jet a CLR proc to run)
is to set the permission level to External_Access...
SQL Server Host Policy Level Permission Sets The set of code access
security permissions granted to assemblies by the SQL Server host
policy level is determined by the permission set specified when
creating the assembly. There are three permission sets: SAFE,
EXTERNAL_ACCESS and UNSAFE.
The permision level is set on the properties pages of the CLR project
, database tab - set Permission Level-External, set Aassembly
Owner-dbo, and run tsql 'ALTER DATABASE DataBaseName SET TRUSTWORTHY
ON' This will get the job DONE! - and the SmtpClient wiill work ok...
Then do it right and Sign the Assenbly with a Strong name Key file...
Full Post Here...
Have you set your DB set to Trusrtworth ON and enabled clr?
Try this
sp_configure 'clr enabled', 1
GO
RECONFIGURE
GO
ALTER DATABASE [YourDatabase] SET TRUSTWORTHY ON
GO
I have a guide here on how to use CLR Stored Procedures that might help.

Resources