当我尝试运行以下代码时,出现以下错误。尝试引用其他帖子,但似乎无济于事。
在当前安全性上下文下,服务器主体“ {Myuser}”无法访问数据库“ {database}”。 (916)(SQLExecDirectW)'
import pyodbc
cnxn = pyodbc.connect("Driver={SQL Server};"
'Server=XXXXXXX;'
'Port=xxxx'
'Username={service_account}'
'Password={password of service_account}'
'Database={detabase};'
'Trusted_Connection=yes;')
results = cnxn.cursor()
results.execute('SELECT * FROM {database}.dbo.{tablename}')
for row in results:
print(row)
答案 0 :(得分:1)
如果要将Microsoft的ODBC驱动程序用于SQL Server和from django.views import View
from django.http import HttpResponse
from django.contrib.gis.geoip2 import GeoIP2
from .models import Victims, Url
g = GeoIP2()
def Get_Ip(request):
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[-1].strip()
else:
ip = request.META.get('REMOTE_ADDR')
return ip
def Get_Country(request):
ip = Get_Ip(request)
country = g.country('31.13.75.36')
return country
def Get_Browser(request):
browser = request.META['HTTP_USER_AGENT']
return browser
def save_vistor_data(request, slug):
ip = Get_Ip(request)
country = Get_Country(request)
browser = Get_Browser(request)
_url = Url()
url = Url.objects.get(slug=slug)
victim = Victims(_url=url, ip_address=ip, country=country, browser=browser)
victim.save()
return HttpResponse('Done')
(SQL Server Windows身份验证),则不会在连接字符串中传递Windows凭据。相反,您以Windows用户身份运行Python应用程序。做到这一点的方法包括
Trusted_Connection=yes
命令从Windows命令提示符下启动Python应用,或者另一个选择是使用FreeTDS ODBC驱动程序。它支持较旧的NTLM身份验证协议,并允许您在连接字符串中指定DOMAIN,UID和PWD(用于Windows身份验证)。
答案 1 :(得分:0)
这对我有用:
import pyodbc
password = "<password>"
conn = pyodbc.connect("Driver={SQL Server};Server=<host>;Port=<port>;UID=
<username>;PWD=" + password + ";Database=<dbname>;")
cursor = conn.cursor()
cursor.execute('SELECT * FROM <table>')
for row in cursor:
print(row)