如何让Python连接到SQL Server数据库

问题描述 投票:0回答:1

你好,我正在尝试将 python 连接到 sql server,但只能连接到 master dtabase 等系统数据库,我无法连接到我的数据库,有人知道我如何配置我的数据库以在 python 中连接?

import pyodbc as odbc
DRIVER_NAME ='SQL SERVER'
SERVER_NAME='BOOK-FFARDRU9TD'
DATABASE_NAME='Teste' #dosent work with my datavbases
NAME='pierre'
PASS='987652'
connection_string=f"""
    DRIVER={{{DRIVER_NAME}}};
    SERVER={SERVER_NAME};
    DATABASE={DATABASE_NAME};
    Trusted_Connection= yes;
    UID={NAME};
    PWD={PASS};
    """
conn=odbc.connect(connection_string)
print("aaaaaaaaaaa")

错误是:

pyodbc. ProgrammingError: ('42000', '[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Unable to open the "Teste" database requested by logon. Logon failed. (4060) (SQLDriverConnect); [42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Unable to open the "Teste" database prompted by logon. Logon failed. (4060)')

我需要帮助来解决这个问题,我认为我尝试用来访问数据库的用户没有权限,但我不知道该怎么做。

python sql-server-2008 odbc
1个回答
0
投票

错误消息提到了一个名为“Test”的数据库,但在代码中它被写为“Teste”。

在 SQL 查询中,您可以使用以下行向指定用户授予数据库权限:

USE ML_Samples //Database name
GO
EXEC sp_addrolemember 'db_datareader', 'MySQLLogin' //User name

https://learn.microsoft.com/en-us/sql/machine-learning/security/user-permission?view=sql-server-ver16

© www.soinside.com 2019 - 2024. All rights reserved.