连接数据库实现登陆 增删改查
时间: 2023-07-03 16:16:06 浏览: 90
c#登陆界面与Oracle数据库连接并增删改查
好的,首先需要连接数据库实现登陆、增删改查功能,可以使用Python的MySQL数据库模块进行实现。以下是一个简单的示例代码:
```python
import mysql.connector
# 连接数据库
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
# 创建游标对象
mycursor = mydb.cursor()
# 登陆功能
def login(username, password):
sql = "SELECT * FROM users WHERE username = %s AND password = %s"
val = (username, password)
mycursor.execute(sql, val)
result = mycursor.fetchone()
if result:
print("登陆成功!")
else:
print("登陆失败,请检查用户名和密码!")
# 增加数据
def add_data(name, age, gender):
sql = "INSERT INTO students (name, age, gender) VALUES (%s, %s, %s)"
val = (name, age, gender)
mycursor.execute(sql, val)
mydb.commit()
print("添加数据成功!")
# 删除数据
def delete_data(name):
sql = "DELETE FROM students WHERE name = %s"
val = (name,)
mycursor.execute(sql, val)
mydb.commit()
print("删除数据成功!")
# 修改数据
def update_data(name, age, gender):
sql = "UPDATE students SET age = %s, gender = %s WHERE name = %s"
val = (age, gender, name)
mycursor.execute(sql, val)
mydb.commit()
print("修改数据成功!")
# 查询数据
def query_data():
sql = "SELECT * FROM students"
mycursor.execute(sql)
result = mycursor.fetchall()
for row in result:
print(row)
# 测试
login("admin", "123456")
add_data("Tom", 20, "Male")
delete_data("Tom")
update_data("Jack", 22, "Male")
query_data()
```
以上代码连接了MySQL数据库,并实现了登陆、增删改查功能。您可以根据自己的需求进行修改。
阅读全文