Authentifizierung in Azure aus Python
Posted: 28 Mar 2025, 14:10
Ich versuche, eine Verbindung von Python zum Azure Server herzustellen, um eine Tabelle in Azure hochzuladen. < /p>
Mein Code: < /p>
Ich habe geprüft und
[*] Ich habe den Treiber -ODBC -Treiber 18 für SQL -Server installiert
[*] pwd und Benutzer sind korrekt
Server und DB sind richtig.>
Mein Code: < /p>
Code: Select all
def create_and_store_dataframe_to_azure(df, table_name, server, database, password, driver="ODBC Driver 18 for SQL Server", schema='dbo'):
try:
params = quote_plus(
f"DRIVER={driver};SERVER={server},1433;DATABASE={database};UID={username}@myazure.windows.net;PWD={password};Encrypt=yes;TrustServerCertificate=no;Connection Timeout=60;"
)
engine = sqlalchemy.create_engine(f"mssql+pyodbc:///?odbc_connect={params}")
column_types = {
'int64': 'BIGINT',
'float64': 'FLOAT',
'object': 'NVARCHAR(MAX)',
'bool': 'BIT',
'datetime64[ns]': 'DATETIME'
}
create_table_query = f"CREATE TABLE {schema}.{table_name} ("
for col in df.columns:
col_type = column_types.get(str(df[col].dtype), 'NVARCHAR(MAX)') # Default to NVARCHAR if type unknown
create_table_query += f"[{col}] {col_type}, "
create_table_query += "[InsertedTimestamp] DATETIME DEFAULT GETDATE() );"
with engine.begin() as conn:
conn.execute(text(f"DROP TABLE IF EXISTS {schema}.{table_name}")) # Drop table if it exists
conn.execute(text(create_table_query))
print(f"Table {schema}.{table_name} created successfully.")
df = df.drop(columns=['InsertedTimestamp'], errors='ignore')
df.to_sql(name=table_name, con=engine, schema=schema, if_exists='append', index=False, method="multi", chunksize=50)
print(f"Data successfully inserted into {schema}.{table_name}")
except Exception as e:
print(f"Error creating or inserting data into Azure SQL: {e}")
server = "myazure.windows.net"
database = "DB"
driver = "ODBC Driver 18 for SQL Server"
username = "[email protected]"
authentication = "ActiveDirectoryInteractive"
password = "mypwd"
< /code>
Aber beim Ausführen der Funktion erhalte ich den folgenden Fehler: < /p>
Error creating or inserting data into Azure SQL: (pyodbc.InterfaceError) ('28000', "[28000] [Microsoft][ODBC Driver 18 for SQL Server][SQL Server]Login failed for user '[email protected]'. (18456) (SQLDriverConnect); [28000] [Microsoft][ODBC Driver 18 for SQL Server]Invalid connection string attribute (0); [28000] [Microsoft][ODBC Driver 18 for SQL Server][SQL Server]Login failed for user '[email protected]'. (18456); [28000] [Microsoft][ODBC Driver 18 for SQL Server]Invalid connection string attribute (0)")
[*] Ich habe den Treiber -ODBC -Treiber 18 für SQL -Server installiert
[*] pwd und Benutzer sind korrekt
Server und DB sind richtig.>