用pymysql实现的注册登录公告练习

import pymysql

#1.连接服务器
conn=pymysql.connect(
    host='127.0.0.1',
    port=3306,
    user='root',
    password='123456',
    database='公告'
)

#2.通过连接拿到游标对象
#默认的游标返回的是元祖类型,不方便使用,需要更换字典类型的游标
c=conn.cursor(pymysql.cursors.DictCursor)

is_login=[None]

def login_auth(func):
    def wrapper(*args, **kwargs):
        while not is_login[0]:
            print('请先登录')
            login(c,conn)
        res=func(*args,**kwargs)
        return res
    return wrapper


#用户注册
def register(c,conn):
    while True:
        print('欢迎来到注册')
        #输入用户信息
        username=input('输入你的用户名:')
        pwd=input('输入你的密码:')

        #3.执行sql
        sql='select * from user where username=%s'

        if c.execute(sql,(username,)):
            print('用户名已存在,请重新输入!')
            continue
        else:
            sql2='insert into user(username,pwd) values(%s,%s)'
            if c.execute(sql2,(username,pwd)):
                print('注册成功!')
                conn.commit()
                break
            else:
                print('注册失败')
                continue

#用户登录
def login(c,conn):
    global is_login
    if is_login[0]:
        print('已经登录了不用再登录')
        return
    while True:
        print('欢迎来到登录')
        #输入用户信息
        username=input('输入你的用户名:')
        pwd=input('输入你的密码:')
        sql='select * from user where username=%s and pwd=%s'
        rec=c.execute(sql,(username,pwd))
        if c.fetchall():
            print('登录成功')
            conn.commit()
            is_login[0]=1
            break
        else:
            print('账号密码错误')


#发布公告
@login_auth
def post_notice(c,conn):
    print('欢迎来到发布公告')
    notice_titile=input('请输入你要发布的公告标题:')
    notice_content= input('请输入你要发布的公告内容:')

    #执行sql
    sql='insert into notice(titile,content) values(%s,%s)'
    c.execute(sql,(notice_titile,notice_content))
    print('公告发布成功')
    conn.commit()

#查看公告
@login_auth
def show_notice(c,conn):
    print('欢迎来到查看公告')
    sql='select * from notice'
    c.execute(sql)
    print(c.fetchall())
    conn.commit()


func_list={
    1:register,
    2:login,
    3:post_notice,
    4:show_notice
}

func_list_view='''
    1:register,
    2:login,
    3:post_notice,
    4:show_notice
    5:quit
    '''

while True:
    print(func_list_view)
    choice=input('请选择功能:')
    if choice=='5':
        break
    else:
        choice=int(choice)
        func_list[choice](c,conn)
原文地址:https://www.cnblogs.com/zhoajiahao/p/11215736.html