python 连接sqlserver
时间: 2023-09-05 08:14:08 浏览: 111
要使用Python连接到SQL Server数据库,需要安装pyodbc库。安装完成后,可以按照以下步骤进行连接:
1. 导入pyodbc库
```python
import pyodbc
```
2. 定义连接字符串
```python
server = 'your_server_name'
database = 'your_database_name'
username = 'your_username'
password = 'your_password'
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+password)
```
3. 创建游标
```python
cursor = cnxn.cursor()
```
4. 执行SQL查询
```python
cursor.execute('SELECT * FROM your_table_name')
```
5. 获取查询结果
```python
for row in cursor:
print(row)
```
6. 关闭连接
```python
cnxn.close()
```
完整代码示例:
```python
import pyodbc
server = 'your_server_name'
database = 'your_database_name'
username = 'your_username'
password = 'your_password'
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+password)
cursor = cnxn.cursor()
cursor.execute('SELECT * FROM your_table_name')
for row in cursor:
print(row)
cnxn.close()
```
阅读全文