python连接mysql数据库

例子:判断用户是否登录成功
1 import pymysql 2 import hashlib 3 4 class Consql(): 5 def __init__(self): 6 self.db = pymysql.connect(host='localhost', port=3306, user='root', password='mysql123', db='book') 7 self.cursor = self.db.cursor() 8 9 def close_sql(self): 10 self.cursor.close() 11 self.db.close() 12 13 #增删改数据库 14 def operate_sql(self,sql): 15 self.cursor.execute(sql) 16 self.db.commit() 17 18 self.close_sql() 19 20 #查询数据库 21 def select_all_sql(self,sql): 22 self.cursor.execute(sql) 23 content =self.cursor.fetchall() 24 25 self.close_sql() 26 return content 27 28 if __name__ == '__main__': 29 con=Consql() 30 # #创建/修改表 31 # create_table='create table test_user(id int auto_increment primary key not null,name varchar(20),password char(35));' 32 # con.operate_sql(create_table) 33 # alter_sql='alter table test_user modify password char(32)' 34 # con.operate_sql(alter_sql) 35 36 37 # #插入数据 38 # insert_sql="insert into test_user(name,password) values('cherry','c7a4476fc64b75ead800da9ea2b7d072')" 39 # con.operate_sql(insert_sql) 40 41 #判断用户是否存在及密码是否正确 42 user=input('请输入用户名:') 43 pwd=input('请输入密码:') 44 #将输入的密码加密 45 m=hashlib.md5() 46 m.update(pwd.encode('utf-8')) 47 s=m.hexdigest() 48 # print(s) 49 50 select_sql='select password from test_user where name="{}";'.format(user) 51 result=con.select_all_sql(select_sql) 52 # print(result) 53 54 if len(result)==0: 55 print('用户不存在') 56 elif result[0][0]==s: 57 print('登录成功') 58 else: 59 print('密码不正确')
posted on 2019-10-19 10:32 cherry_ning 阅读(132) 评论(0) 收藏 举报
浙公网安备 33010602011771号