macOS
⚠️ Always review any code before running it on your system.
Installing Homebrew
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
📘 Homebrew
Homebrew is a popular package manager for macOS that simplifies the installation of software and development tools.
At the time of writing this guide, it is the method recommended by Microsoft for installing the ODBC driver for SQL Server 18.
Installing the Microsoft ODBC driver for SQL Server
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"
brew tap microsoft/mssql-release https://github.com/Microsoft/homebrew-mssql-release
brew update
HOMEBREW_ACCEPT_EULA=Y brew install msodbcsql18 mssql-tools18
📘 OIDBC
ODBC (Open Database Connectivity) is a standard interface that allows applications to connect to databases.
Since SQL Server is a Microsoft product primarily designed for Windows environments, connecting from macOS requires Microsoft’s official ODBC driver to act as a translator between your Mac applications and the SQL Server database.
Python
Connect to a SQL Server database. Requires an environment file.
📝 environment.txt
DB_SERVER=sql.example.com
DB_NAME=example
DB_USERNAME=user
DB_PASSWORD=pass
DB_SCHEMA=ALL
DB_TABLE=data
import os
import pyodbc
def load_env(filename):
"""Load environment variables from a file."""
try:
with open(filename, 'r', encoding='utf-8') as file:
for line in file.readlines():
line = line.rstrip('\n')
if line and '=' in line:
key, value = line.split('=', 1)
os.environ[key] = value
print(f"Setting {key}: {repr(value)}")
except FileNotFoundError:
print(f"Error: Environment file '{filename}' not found")
exit(1)
except Exception as e:
print(f"Error reading environment file: {e}")
exit(1)
def main():
# Load environment variables
load_env('.env')
# Construct connection string
conn_str = (
f"DRIVER={{ODBC Driver 18 for SQL Server}};"
f"SERVER={os.getenv('DB_SERVER')};"
f"DATABASE={os.getenv('DB_NAME')};"
fr"UID={os.getenv('DB_USERNAME')};"
f"PWD={os.getenv('DB_PASSWORD')};"
"TrustServerCertificate=yes"
)
try:
# Connect to the database
conn = pyodbc.connect(conn_str)
cursor = conn.cursor()
# Execute query
query = f"SELECT TOP 1 * FROM [{os.getenv('DB_SCHEMA')}].[{os.getenv('DB_TABLE')}]"
cursor.execute(query)
# Get column names
columns = [column[0] for column in cursor.description]
# Fetch and print results
for row in cursor.fetchall():
for col_name, value in zip(columns, row):
print(f"{col_name}: {value}")
print("-" * 50)
except pyodbc.Error as e:
print(f"Database error: {e}")
except Exception as e:
print(f"Error: {e}")
finally:
if 'conn' in locals():
conn.close()
if __name__ == "__main__":
main()
R
Connect to a SQL Server database. Requires an environment file.
📝 environment.txt
DB_SERVER=sql.example.com
DB_NAME=example
DB_USERNAME=user
DB_PASSWORD=pass
DB_SCHEMA=ALL
DB_TABLE=data
library(DBI)
library(odbc)
library(dotenv)
# Function to load environment variables
load_env <- function(filename) {
if (!file.exists(filename)) {
stop("Environment file not found")
}
env_lines <- readLines(filename)
for (line in env_lines) {
if (nchar(trimws(line)) > 0 && !startsWith(trimws(line), "#")) {
parts <- strsplit(line, "=", fixed = TRUE)[[1]]
if (length(parts) == 2) {
var_name <- trimws(parts[1])
var_value <- trimws(parts[2])
do.call(Sys.setenv, structure(list(var_value), names = var_name))
}
}
}
}
main <- function() {
# Load environment variables
load_env("environment.txt")
# Create connection string
conn <- dbConnect(odbc::odbc(),
Driver = "/opt/homebrew/lib/libmsodbcsql.18.dylib",
Server = Sys.getenv("DB_SERVER"),
Database = Sys.getenv("DB_NAME"),
UID = Sys.getenv("DB_USERNAME"),
PWD = Sys.getenv("DB_PASSWORD"),
TrustServerCertificate = "yes"
)
# Ensure connection is closed when function exits
on.exit(dbDisconnect(conn))
# Construct and execute query
query <- sprintf("SELECT TOP 1 * FROM [%s].[%s]",
Sys.getenv("DB_SCHEMA"),
Sys.getenv("DB_TABLE"))
# Execute query
tryCatch({
result <- dbGetQuery(conn, query)
# Print results
for (col in names(result)) {
cat(sprintf("%s: %s\n", col, result[[col]][1]))
}
}, error = function(e) {
stop(sprintf("Query execution failed: %s", e$message))
})
}
main()
Windows
⚠️ Always review any code before running it on your system.
Installing the Microsoft ODBC driver for SQL Server
- Download the ODBC for your system driver here (most likely the ‘x64’ version)
- Install it
📘 OIDBC
ODBC (Open Database Connectivity) is a standard interface that allows applications to connect to databases.
Python
Connecting to the BIGFI server
📝 environment.txt
DB_SERVER=sql.example.com
DB_NAME=example
DB_USERNAME=user
DB_PASSWORD=pass
DB_SCHEMA=ALL
DB_TABLE=data
R
📝 environment.txt
DB_SERVER=sql.example.com
DB_NAME=example
DB_USERNAME=user
DB_PASSWORD=pass
DB_SCHEMA=ALL
DB_TABLE=data
Connecting to the BIGFI server