python连接sqlserver数据库_Python基于Pymssql模块实现通讯录管理系统
时间: 2023-07-20 16:08:33 浏览: 185
python通讯录(含数据库)
好的,下面是Python基于Pymssql模块实现通讯录管理系统的教程。
1.安装Pymssql模块
```
pip install pymssql
```
2.创建数据库和表
首先需要在SQL Server中创建一个数据库,并且创建一个名为“contacts”的表,用于存储联系人的信息。
```sql
CREATE DATABASE ContactDB;
GO
USE ContactDB;
GO
CREATE TABLE contacts (
id INT PRIMARY KEY IDENTITY,
name VARCHAR(50) NOT NULL,
phone VARCHAR(50) NOT NULL,
email VARCHAR(50) NOT NULL
);
GO
```
3.连接数据库并实现增删改查功能
```python
import pymssql
class Contacts:
def __init__(self, server, username, password, database):
self.server = server
self.username = username
self.password = password
self.database = database
def connect(self):
self.conn = pymssql.connect(server=self.server, user=self.username,
password=self.password, database=self.database)
def add_contact(self, name, phone, email):
self.connect()
cursor = self.conn.cursor()
sql = "INSERT INTO contacts (name, phone, email) VALUES (%s, %s, %s)"
cursor.execute(sql, (name, phone, email))
self.conn.commit()
self.conn.close()
def get_contacts(self):
self.connect()
cursor = self.conn.cursor()
sql = "SELECT * FROM contacts"
cursor.execute(sql)
rows = cursor.fetchall()
self.conn.close()
return rows
def update_contact(self, id, name, phone, email):
self.connect()
cursor = self.conn.cursor()
sql = "UPDATE contacts SET name=%s, phone=%s, email=%s WHERE id=%s"
cursor.execute(sql, (name, phone, email, id))
self.conn.commit()
self.conn.close()
def delete_contact(self, id):
self.connect()
cursor = self.conn.cursor()
sql = "DELETE FROM contacts WHERE id=%s"
cursor.execute(sql, (id,))
self.conn.commit()
self.conn.close()
```
4.编写用户交互界面
```python
def main():
contacts = Contacts(server='localhost', username='sa', password='password', database='ContactDB')
while True:
print("1. 添加联系人")
print("2. 查看联系人")
print("3. 修改联系人")
print("4. 删除联系人")
print("5. 退出")
choice = input("请输入要执行的操作:")
if choice == '1':
name = input("请输入姓名:")
phone = input("请输入电话:")
email = input("请输入邮箱:")
contacts.add_contact(name, phone, email)
print("联系人添加成功!\n")
elif choice == '2':
rows = contacts.get_contacts()
print("所有联系人:")
for row in rows:
print(row)
elif choice == '3':
id = input("请输入要修改的联系人ID:")
name = input("请输入姓名:")
phone = input("请输入电话:")
email = input("请输入邮箱:")
contacts.update_contact(id, name, phone, email)
print("联系人修改成功!\n")
elif choice == '4':
id = input("请输入要删除的联系人ID:")
contacts.delete_contact(id)
print("联系人删除成功!\n")
elif choice == '5':
exit()
else:
print("请输入正确的操作!\n")
if __name__ == '__main__':
main()
```
以上就是Python基于Pymssql模块实现通讯录管理系统的教程,希望能对你有所帮助。
阅读全文