先在mysql中建立乙個資料庫,這裡資料庫名為py_demo
建立乙個表,這裡名為py_users
create table py_users(
id int unsigned auto_increment not null primary key,
uname varchar(20) not null,
upwd char(40) not null,
is_delete bit not null default 0
使用者註冊處理流程
1.png
使用者登陸處理流程
2.png
下面是**
coding = utf-8
匯入pymysql
from pymysql import *
匯入加密包
from hashlib import *
定義乙個conn
conn = none
cur = none
註冊def register():
# 新增異常
try:
conn = mysql_conn()
# 游標
cur = conn.cursor()
select_params = [username]
select_sql = 'select * from py_users where uname = %s'
# execute(sql檔案,[params引數])
cur.execute(select_sql,select_params)
ret = cur.fetchone()
# print(ret)
# 判斷ret返回的值,如果返回的不是none,則證明註冊失敗
if ret is not none:
print('使用者名稱已存在')
return
#如果返回的是none,則證明使用者名稱沒有被註冊,進行下一步
#插入資料到資料庫
insert_params = [username,sha_pwd]
insert_sql = 'insert into py_users values (0,%s,%s,0)'
count = cur.execute(insert_sql,insert_params)
#count 返回的是受影響的行,如果返回的是0,證明沒有插入成功
if count == 0:
print('註冊失敗')
else:
print('註冊成功')
# 關閉事務
conn.commit()
except exception as ex:
print(ex)
finally:
close(conn,cur)
登陸def login():
# 新增異常
try:
conn = mysql_conn()
cur = conn.cursor()
parmas = [username]
# 因為後面要判斷密碼,所有最好查詢upwd,便於判斷
select_sql = 'select upwd from py_users where uname = %s'
cur.execute(select_sql,parmas)
res = cur.fetchone()
#如果res 返回的是none,證明沒有使用者名稱,登入失敗
if res is none:
print('登入失敗,使用者名稱或密碼錯誤!')
return
# print(res[0])
#res返回的是乙個元祖,所以要取得輸入密碼的sha1,res[0]得到的是輸入密碼的加密格式,判斷和資料庫中密碼是否一樣
# 定義乙個pwd變數,取得密碼的加密格式
pwd = res[0]
if pwd == sha_pwd:
print('登入成功')
else:
print('登入失敗,使用者名稱或密碼錯誤!')
except exception as ex:
print(ex)
finally:
close(conn,cur)
連線資料庫
def mysql_conn():
return connect(host='localhost',port=3306,user='root',password='123456',database='py_demo',charset='utf8')
關閉def close(conn,cur):
cur.close()
conn.close()
if name == 'main':
username = input('請輸入使用者名稱:')
userpwd = input('請輸入使用者密碼:')
s1 = sha1()
s1.update(userpwd.encode())
sha_pwd = s1.hexdigest()
# print(sha_pwd)
# register()
login()
mysql使用者變數 MySQL使用者變數的用法
mysql資料庫中的變數分為mysql系統變數和mysql使用者變數,下面就為您介紹mysql使用者變數的應用,供您參考學習之用。mysql使用者變數 基於會話變數實現的,可以暫存值,並傳遞給同一連線裡的下一條sql使用的變數.當客戶端連線退出時,變數會被釋放.mysql使用者變數應用場景 同一連線...
mysql使用者執行緒 MySQL 使用者連線與使用者執行緒
pig已經好長一段時間沒有分享文章了,有點對不起訂閱的朋友。最近在做比較複雜跟困難的事情,也並不一定最終會有成果,因此必須對此沉默。停了一段時間,現在定個小目標 2個星期至少寫一篇小文章,簡單講清楚乙個小細節。希望自己最後堅持下來。回題,mysql是多執行緒的資料庫,每個應用會話連線到資料庫時,會使...
mysql 新建使用者遠端登入
mysql 新建的使用者預設是不能遠端登入的。可以通過root帳號登入mysql然後執行 下面命令。grant all privileges on to 使用者名稱 identified by 登入密碼 with grant option 例 grant all privileges on to r...