I am trying to make connection through Azure Databricks to Azure SQL Server and if database is not available, then create a new one and same for table but getting error for ODBC driver
How to install ‘ODBC Driver 17 for SQL Server" in an Azure Databricks workspace?
%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()
2
Answers
To install MS SQL ODBC Driver on Azure Databricks workspace run below command in a single cell.
To install ODBC Driver 17 for SQL Server on databricks cluster you can follow below steps: