如何使用python 连接 SQL Server Management Studio
时间: 2025-06-12 10:46:04 浏览: 12
### 使用 Python 连接 SQL Server Management Studio 的方法和代码示例
连接 SQL Server Management Studio (SSMS) 可以通过多种方式实现,其中包括使用 `pyodbc` 或 `pymssql` 等库。以下将详细介绍这两种方法,并提供相应的代码示例。
---
#### 方法一:使用 `pyodbc` 连接 SQL Server
`pyodbc` 是一个常用的库,用于在 Python 中与数据库进行交互。以下是具体的代码示例:
```python
import pyodbc
# 定义连接字符串
connection_string = (
"Driver={ODBC Driver 17 for SQL Server};"
"Server=your_server_name;" # 替换为你的服务器名称
"Database=SQL Tutorial;" # 替换为你的数据库名称
"Trusted_Connection=Yes;" # 使用 Windows 身份验证
)
try:
# 建立连接
connection = pyodbc.connect(connection_string)
cursor = connection.cursor()
# 执行查询
query = "SELECT * FROM dbo.booking"
cursor.execute(query)
# 获取结果并打印前几行
rows = cursor.fetchall()
for row in rows[:5]:
print(row)
except Exception as e:
print(f"Error: {e}")
finally:
# 关闭连接
if 'connection' in locals():
connection.close()
```
上述代码中,`Trusted_Connection=Yes` 表示使用 Windows 身份验证[^4]。如果需要使用 SQL Server 身份验证,则需替换为用户名和密码,例如:
```python
connection_string = (
"Driver={ODBC Driver 17 for SQL Server};"
"Server=your_server_name;"
"Database=SQL Tutorial;"
"UID=sa;" # 用户名
"PWD=your_password;" # 密码
)
```
---
#### 方法二:使用 `pymssql` 连接 SQL Server
`pymssql` 是另一个流行的库,用于连接 SQL Server 数据库。以下是具体代码示例:
```python
import pymssql
try:
# 建立连接
connection = pymssql.connect(
server='LAPTOP-A8GKG26P', # 替换为你的服务器名称
user='sa', # 替换为你的用户名
password='123456', # 替换为你的密码
database='EDUC' # 替换为你的数据库名称
)
# 创建游标对象
cursor = connection.cursor()
# 执行查询
cursor.execute("SELECT * FROM dbo.booking")
# 获取结果并打印前几行
rows = cursor.fetchall()
for row in rows[:5]:
print(row)
except Exception as e:
print(f"Error: {e}")
finally:
# 关闭连接
if 'connection' in locals():
connection.close()
```
此代码展示了如何通过 `pymssql.connect()` 函数连接到 SQL Server,并执行查询操作[^2]。
---
#### 注意事项
1. 在使用 SQL Server 身份验证时,确保已设置正确的用户名和密码,并取消强制实施密码策略[^4]。
2. 如果遇到连接失败的问题,请检查 ODBC 驱动程序是否已正确安装,并确保服务器名称、数据库名称等信息无误。
3. 对于 Windows 身份验证,确保当前用户具有访问 SQL Server 的权限。
---
阅读全文
相关推荐


















