创建一个用户表 字段要求:主键、用户、密、性别、手机号、、删除标识另外用户名不能重复 1、写一个接口将用户信息保存到数据库 2、写一个接口验证用户的密码是否正确
时间: 2023-10-15 22:05:56 浏览: 91
1. 创建用户表的 SQL 语句如下:
```
CREATE TABLE user (
id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(50) NOT NULL UNIQUE,
password VARCHAR(50) NOT NULL,
gender ENUM('male', 'female') NOT NULL,
phone VARCHAR(20) NOT NULL,
is_deleted BOOLEAN NOT NULL DEFAULT FALSE
);
```
2. 实现保存用户信息到数据库的接口:
```python
import pymysql
def save_user(username, password, gender, phone):
conn = pymysql.connect(
host='localhost',
user='root',
password='password',
database='test_db',
charset='utf8mb4'
)
cursor = conn.cursor()
try:
sql = '''
INSERT INTO user (username, password, gender, phone)
VALUES (%s, %s, %s, %s)
'''
cursor.execute(sql, (username, password, gender, phone))
conn.commit()
return True
except Exception as e:
conn.rollback()
print(e)
return False
finally:
cursor.close()
conn.close()
```
3. 实现验证用户密码是否正确的接口:
```python
import pymysql
def check_password(username, password):
conn = pymysql.connect(
host='localhost',
user='root',
password='password',
database='test_db',
charset='utf8mb4'
)
cursor = conn.cursor()
try:
sql = '''
SELECT password FROM user WHERE username = %s
'''
cursor.execute(sql, (username,))
result = cursor.fetchone()
if result and result[0] == password:
return True
else:
return False
except Exception as e:
print(e)
return False
finally:
cursor.close()
conn.close()
```
阅读全文