使用 python 从 Azure 机器学习服务连接 Azure SQL 数据库时出错

Error in connecting Azure SQL database from Azure Machine Learning Service using python

我正在尝试从 Azure 机器学习服务 连接 Azure SQL 数据库,但出现以下错误。

请检查错误:-

**('IM002', '[IM002] [unixODBC][Driver Manager]Data source name not found and no default driver specified (0) (SQLDriverConnect)')**

请检查我用于数据库连接的以下代码:-

import pyodbc

class DbConnect:
    # This class is used for azure database connection using pyodbc
    def __init__(self):
        try:
            self.sql_db = pyodbc.connect(SERVER=<servername>;PORT=1433;DATABASE=<databasename>;UID=<username>;PWD=<password>')

            get_name_query = "select name from contacts"
            names = self.sql_db.execute(get_name_query)
            for name in names:
                print(name)

        except Exception as e:
            print("Error in azure sql server database connection : ", e)
            sys.exit()

if __name__ == "__main__":
    class_obj = DbConnect()

有什么办法可以解决上面的错误吗?有什么办法请告诉我。

我会考虑使用 azureml.dataprep 而不是 pyodbc 来完成这项任务(API 可能会改变,但我上次尝试时它有效):

import azureml.dataprep as dprep

ds = dprep.MSSQLDataSource(server_name=<server-name,port>,
                           database_name=<database-name>,
                           user_name=<username>,
                           password=<password>)

然后您应该能够在 pandas 中收集 SQL 查询的结果,例如通过

dataflow = dprep.read_sql(ds, "SELECT top 100 * FROM [dbo].[MYTABLE]")
dataflow.to_pandas_dataframe()

或者,您可以 create SQL datastore 从 SQL 数据存储区创建数据集。 学习如何: https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-create-register-datasets#create-tabulardatasets

示例代码:

from azureml.core import Dataset, Datastore

# create tabular dataset from a SQL database in datastore
sql_datastore = Datastore.get(workspace, 'mssql')
sql_ds = Dataset.Tabular.from_sql_query((sql_datastore, 'SELECT * FROM my_table'))

@AkshayGodase 您想使用 pyodbc 的任何特定原因?