python-mysql database login and registration exercises

 1 import hashlib,pymysql,datetime
 2 def my_db(sql):
 3     import pymysql
 4     coon = pymysql.connect(
 5         host = '118.24.3.40',user = 'jxz',passwd = '123456',
 6         port = 3306,db = 'jxz',charset = 'utf8'
 7     )
 8     cur = coon.cursor()#建立游标
 9     cur.execute(sql)#Execute sql 
10      if sql.strip()[:6].upper() == ' SELECT ' :
 11          res = cur.fetchall()
 12      else :
 13          coon.commit()
 14          res = ' ok ' 
15      cur.close ()
 16      coon.close()
 17      return res
 18  
19  def my_md5(str):
 20      import hashlib
 21      new_str = str.encode() #Convert the string to bytes type 
22      m = hashlib.md5() #Instantiate md5 object
23     m.update(new_str)#加密
24     return m.hexdigest()#获取返回结果
25 
26 def reg():
27     username = input("username:").strip()
28     pwd = input("pwd:").strip()
29     cpwd = input('cpwd:').strip()
30     if username and pwd and cpwd:
31         sql = 'select * from nhy where name = "%s";'%username
 32          res = my_db(sql)
 33          if res:
 34              print ( " The user already exists! " )
 35          else :
 36              if pwd == cpwd:
 37                  md5_pwd = my_md5(pwd)
 38                  insert_sql = ' insert into nhy (name, pwd) values ​​("%s","%s"); ' % (username,md5_pwd)
 39                  my_db(insert_sql)
 40                  print ( " Registration successful! " )
 41              else :
42                  print ( ' The passwords entered twice are inconsistent! ' )
 43      else :
 44          print ( ' The required fields cannot be empty! ' )
 45  
46  def login():
 47      username = input( ' username: ' ).strip()
 48      pwd = input( ' pwd: ' ).strip()
 49      if username and pwd:
 50          md5_pwd = my_md5(pwd)
 51          sql = ' select * from nhy where name = "%s" and pwd = "%s";' % (username,md5_pwd)
 52          res = my_db(sql)
 53          if res:
 54              print ( " Welcome, successful login! Today is %s " % datetime.date.today())
 55          else :
 56              print ( ' Account or Password error ' )
 57      else :
 58          print ( " Required fields cannot be empty! " )
 59  # login() 
60 reg()

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325573147&siteId=291194637