Python连接Sql server数据库

def parse_subjectname(sid):
    """
        根据传入的sid,连接到SQL Server数据库,并获取对应的subjectname。

        参数:
        sid: int - 要查询的subject的sid

        返回:
        subject_name: str 或 None - 查询到的subjectname,如果没有找到则返回None
        """
    # 固定的数据库连接信息
    server = '***'
    database = '***'
    username = '***'
    password = '***'

    # 构建连接字符串
    conn_str = (
        f'DRIVER={{ODBC Driver 17 for SQL Server}};'
        f'SERVER={server};'
        f'DATABASE={database};'
        f'UID={username};'
        f'PWD={password}'
    )

    try:
        # 建立连接
        with pyodbc.connect(conn_str) as conn:
            print("数据库连接成功!")

            # 创建游标对象
            with conn.cursor() as cursor:
                # 执行SQL语句
                cursor.execute("SELECT subjectname FROM xj_Subject WHERE sid = ?", (sid,))
                row = cursor.fetchone()  # 使用fetchone()尝试获取单个结果

                # 如果找到结果,返回subjectname,否则返回None
                if row:
                    return row.subjectname
                else:
                    return None

    except Exception as e:
        print("执行过程中发生错误:", e)
        return None

你可能感兴趣的:(数据库,python)