(1)packaging.py 里面封装好方法
import pymysql
import hashlib
class MysqlHelper():
def __init__(self, host, database, user, password, port=3306,charset='utf8'):
self.host = host
self.port = port
self.database = database
self.user = user
self.password = password
self.charset = charset
def connect(self):
self.conn = pymysql.connect(host=self.host, port=self.port, database=self.database, user=self.user, password=self.password,
charset=self.charset)
self.cursor = self.conn.cursor()
def close(self):
self.cursor.close()
self.conn.close()
def select_one(self, sql, params=[]):
result = None
try:
self.connect()
self.cursor.execute(sql, params)
result = self.cursor.fetchone()
self.close()
except Exception as e:
print(e)
return result
def select_all(self, sql, params=[]):
result = ()
try:
self.connect()
self.cursor.execute(sql, params)
result = self.cursor.fetchall()
self.close()
except Exception as e:
print(e)
return result
def __edit(self, sql, params):
count = 0
try:
self.connect()
count = self.cursor.execute(sql, params)
self.conn.commit()
self.close()
except Exception as e:
print(e)
return count
def insert(self, sql, params=[]):
return self.__edit(sql, params)
def update(self, sql, params=[]):
return self.__edit(sql, params)
def delete(self, sql, params=[]):
return self.__edit(sql, params)
def my_md5(self,pwd):
my_md5=hashlib.md5()
my_md5.update(pwd.encode('utf-8'))
return my_md5.hexdigest()
(2)demo04_用户登录案例.py 进行调用
from packaging import MysqlHelper
import hashlib
def register():
name=input('用户名:')
pwd=input('密码:')
helper=MysqlHelper(host='localhost',database='laowang',user='root',password='root')
ret=helper.insert('insert into t_user(name,pwd) VALUES (%s,%s)',[name,helper.my_md5(pwd)])
if ret>0:
print('成功')
else:
print('失败')
def login():
name = input('用户名:')
pwd = input('密码:')
helper = MysqlHelper(host='localhost', database='laowang', user='root', password='root')
ret=helper.select_one('select count(*) from t_user where name=%s and ped=%s',[name,helper.my_md5(pwd)])
if ret[0]>0:
print('成功')
else:
print('失败')
def main():
while True:
choice=input('1、注册1 2、登录')
if choice=='1':
register()
elif choice=='2':
login()
if __name__=='__main__':
main()
附录-数据库 t_user