我正在尝试通过 Azure Databricks 连接到 Azure SQL Server,如果数据库不可用,则创建一个新的数据库并与表相同,但 ODBC 驱动程序出现错误
如何在 Azure Databricks 工作区中安装“ODBC Driver 17 for SQL Server”?
%python
%pip install pyodbc
dbutils.library.restartPython()
import pyodbc
#pending need more work to finish this
#Azure SQL connection details
server = '<Sever-name>'
database = 'master' # Start with the 'master' database for creating a new one
username = 'admin_1'
password = 'test&123'
driver = 'ODBC Driver 17'
# Set up connection string
connection_string = f'DRIVER={driver};SERVER={server};PORT=1433;DATABASE={database};UID={username};PWD={password}'
# Create a connection
conn = pyodbc.connect(connection_string)
cursor = conn.cursor()
# Step 1: Create a new database
new_db_name = 'NewDatabase' # Specify your new database name
cursor.execute(f"CREATE DATABASE {new_db_name}")
conn.commit()
print(f"Database {new_db_name} created successfully!")
# Step 2: Connect to the new database
connection_string_new_db = f'DRIVER={driver};SERVER={server};PORT=1433;DATABASE={new_db_name};UID={username};PWD={password}'
conn_new_db = pyodbc.connect(connection_string_new_db)
print(f"Connected to {new_db_name} successfully!")
# Close the connection
cursor.close()
conn.close()
conn_new_db.close()
要在 Azure Databricks 工作区上安装 MS SQL ODBC 驱动程序,请在单个单元格中运行以下命令。
%sh
curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add -
curl https://packages.microsoft.com/config/ubuntu/22.04/prod.list > /etc/apt/sources.list.d/mssql-release.list
sudo apt-get update
sudo ACCEPT_EULA=Y apt-get -q -y install msodbcsql17