SQLserver里面存放两个表,一个表为user 一个表为userinfo 表user里面存放着username和userpassword 表userinfo里面存放着学号,姓名,性别,出生日期,手机号,住宅,邮箱 在python中连接SQLserver并对这两个数据库进行增删改查
时间: 2024-01-21 17:02:14 浏览: 63
好的,可以的。首先需要安装 `pyodbc` 模块来连接 SQL Server 数据库,可以使用以下命令进行安装:
```
pip install pyodbc
```
接下来,可以使用以下代码连接 SQL Server 数据库并对其中的表进行增删改查操作:
```python
import pyodbc
# 连接 SQL Server 数据库
server = 'localhost' # 数据库服务器名称
database = 'test_db' # 数据库名称
username = 'your_username' # 数据库用户名
password = 'your_password' # 数据库密码
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+password)
# 查询 user 表中的所有数据
cursor = cnxn.cursor()
cursor.execute('SELECT * FROM user')
for row in cursor:
print(row)
# 查询 userinfo 表中的所有数据
cursor.execute('SELECT * FROM userinfo')
for row in cursor:
print(row)
# 插入一条数据到 user 表中
username = 'test_user'
userpassword = 'test_password'
cursor.execute("INSERT INTO user (username, userpassword) VALUES (?, ?)", (username, userpassword))
cnxn.commit()
# 更新 user 表中的一条数据
new_userpassword = 'new_password'
cursor.execute("UPDATE user SET userpassword = ? WHERE username = ?", (new_userpassword, username))
cnxn.commit()
# 删除 user 表中的一条数据
cursor.execute("DELETE FROM user WHERE username = ?", username)
cnxn.commit()
# 关闭连接
cnxn.close()
```
以上代码演示了如何连接 SQL Server 数据库,并对其中的 `user` 和 `userinfo` 两个表进行增删改查操作。你可以根据需要修改表名和字段名,并在代码中添加其他的操作。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![md](https://img-home.csdnimg.cn/images/20250102104920.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)