写个连接SQL server进行增删改查python代码
时间: 2023-02-12 19:33:21 浏览: 254
首先需要安装pyodbc库,可以在命令行中使用pip安装:
```python
pip install pyodbc
```
然后可以使用下面的代码连接SQL Server并进行增删改查操作:
```python
import pyodbc
# 连接数据库
cnxn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=your_server;DATABASE=your_database;UID=your_username;PWD=your_password')
cursor = cnxn.cursor()
# 执行SQL语句
cursor.execute("SELECT * FROM your_table")
# 获取结果
rows = cursor.fetchall()
for row in rows:
print(row)
# 插入数据
cursor.execute("INSERT INTO your_table (column1, column2) VALUES (?, ?)", (value1, value2))
cnxn.commit()
# 更新数据
cursor.execute("UPDATE your_table SET column1 = ? WHERE column2 = ?", (new_value, value))
cnxn.commit()
# 删除数据
cursor.execute("DELETE FROM your_table WHERE column1 = ?", (value))
cnxn.commit()
# 关闭连接
cursor.close()
cnxn.close()
```
请注意,需要将上面代码中的 "your_server","your_database","your_username","your_password","your_table","column1","column2"替换为你自己的信息。
阅读全文