SQL 连接字符串到函数

SQL connection string into function

我正在尝试将连接字符串放入数据库连接函数中:

conn = pyodbc.connect('Driver={SQL Server Native Client 11.0};'
                      'Server=trve-tl'
                      'Database=team;'
                      'Trusted_Connection=yes;')

with open("bike.sql", "r") as file:
    query = file.read()

我尝试创建一个函数如下:

def get_connection(server:str, Database:str)->str:
    global conn = pyodbc.connect('Driver={SQL Server Native Client 11.0};'
                      'Server='+server+';'
                      'Database='+Database+';'
                      'Trusted_Connection=yes;')
    return conn

    

我收到以下错误:

global conn = pyodbc.connect('Driver={SQL Server Native Client 11.0};' ^ SyntaxError: invalid syntax

您需要从 conn 变量声明中删除 'global' 关键字,然后将函数的输出存储在一个新变量中。

def get_connection(server:str, Database:str)->str:
conn = pyodbc.connect('Driver={SQL Server Native Client 11.0};'
                  'Server='+server+';'
                  'Database='+Database+';'
                  'Trusted_Connection=yes;')
return conn

然后这样称呼它

cn = get_connection("localhost","MyDB")
cn.close()