Python on Mac 连接 SQLServer

1 安装 ODBC Driver

$ /usr/bin/ruby -e “$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)“
$ brew tap microsoft/msodbcsql https://github.com/Microsoft/homebrew-mssql-release
$ brew update
$ brew install msodbcsql
// for silent install ACCEPT_EULA=y brew install msodbcsql 

2 安装 pyodbc 库

$ pip install pyodbc

3 连接数据库

import pyodbc
conn_str = 'DRIVER=ODBC Driver 13 for SQL Server;SERVER=10.20.213.10;PORT=1433;DATABASE=csc1002;UID=csc1002;PWD=csc1002'
connection = pyodbc.connect(conn_str)

4 查询数据

sql = 'SELECT * FROM lgu.course;'
cursor = connection.cursor()
with connection:
    rows = cursor.execute().fetchall()
    for row in rows:
        print(row.cursor_description)
        print(row.course_id, row.title, row.dept_name)