python操作数据库的基本步骤:
首先打开local,,创建qqq数据库。
新建查询,输入sql语句创建sh_users表
1 create table sh_users( 2 id int unsigned primary key auto_increment not null, 3 username varchar(20) not null, 4 password char(40) not null, 5 is_delete bit default 0
6 )
刷新表页面,输入sql语句尝试插入
1 insert into sh_users (username, password) values ('r速22t', 'f74e2')
接下来就可以写代码了!
1 from hashlib import *
2 import pymysql 3
4
5 # 获取数据库连接对象
6 def mysql_conn(): 7 conn = pymysql.connect(host='127.0.0.1', user='root', passwd='111111', db='qqq') 8 return conn 9
10
11 def register(): 12 try: 13 # 获取数据库连接对象
14 conn = mysql_conn() 15 # 获取数据库操作cursor(游标)
16 cur = conn.cursor() 17 # 编写查询的sql语句
18 select_sql = f'select password from sh_users where username = "{u_name}"'
19 # 执行sql语句
20 cur.execute(select_sql) 21 # 获取执行结果 fetch_one(),判断结果
22 res = cur.fetchone() 23 # 如果res返回None 表示没有找到数据,不存在可注册,存在注册失败
24 if res is not None: 25 print('用户名已存在,注册失败', res) 26 else: 27 print('该用户名可以使用') 28 # 注册-> 插入数据,手动commit
29 insert_sql = 'insert into sh_users (username, password) values (%s,%s)'
30 insert_params = [u_name, sha_pwd] 31 cur.execute(insert_sql, insert_params) 32 conn.commit() 33 print('注册成功', u_name) 34 # 关闭连接
35 cur.close() 36 conn.close() 37 except Exception as e: 38 print(e) 39
40
41 def login(): 42 try: 43 conn = mysql_conn() 44 cur = conn.cursor() 45 select_sql = f'select password from sh_users where username = "{u_name}"'
46 cur.execute(select_sql) 47 res = cur.fetchone() 48 if res is None: 49 # 登录:根据用户名没有获取密码
50 print('用户名错误,登录失败') 51 else: 52 # res有值,用户名正确,判断密码正确与否
53 m_pwd = res[0] 54 print(m_pwd, '===========================') 55 if m_pwd == sha_pwd: 56 print('登录成功', u_name) 57 else: 58 print('密码错误,登录失败') 59 # 关闭连接
60 cur.close() 61 conn.close() 62 except Exception as e: 63 print(e) 64
65
66 if __name__ == '__main__': 67 u_name = input('请输入用户名') 68 u_pwd = input('请输入密码') 69
70 # sha1加密
71 s1 = sha1() 72 s1.update(u_pwd.encode()) 73 sha_pwd = s1.hexdigest() 74 print(sha_pwd) 75
76 # register()
77 login()
这里用了两种字符串格式化操作,sql语句里“=”号后的引号要注意