MySQL数据库04--python操作数据库

# 1.导入模块
import pymysql


class MysqlHelper(object):
    def __init__(self) -> None:
        self.con = None
        self.cur = None
        try:
            # 2.建立连接
            self.con = pymysql.Connect(user="root", password="123456", database="goods")
            # 3.创建游标

            self.cur = self.con.cursor()
        except Exception as e:
            print(e)

    # 查询一条
    def one(self, query, args=None):
        try:
            self.cur.execute(query, args)
            return self.cur.fetchone()
        except Exception as e:
            print(e)
        finally:
            self._close()

    # 查询n条
    def many(self, query, args=None):
        try:
            self.cur.execute(query, args)
            n = int(input("请输入查询数据条数"))
            return self.cur.fetchmany(size=n)
        except Exception as e:
            print(e)
        finally:
            self._close()

    # 查询所有数据
    def all(self, query, args=None):
        try:
            self.cur.execute(query, args)
            return self.cur.fetchall()
        except Exception as e:
            print(e)
        finally:
            self._close()

    # 关闭连接,关闭游标
    def _close(self):
        if self.cur is not None:
            self.cur.close()
        if self.con is not None:
            self.con.close()

    # 修改增加数据
    def update(self, query, args=None):
        try:
            self.cur.execute(query, args)
            self.con.commit()
        except Exception as e:
            print(e)
        finally:
            self._close()
from homework18 import mysqlhelper
from hashlib import md5
# ————————————————————————————————————————————————————————————
# print(mysqlhelper.MysqlHelper().one("select * from goods"))
# print(mysqlhelper.MysqlHelper().many("select * from goods"))
# print(mysqlhelper.MysqlHelper().all("select * from goods"))
# mysqlhelper.MysqlHelper().update("insert into goods values(0,'aa',100)")

# ————————————————————————————登录————————————————————————————————
count = 0
while True:
    name = input("请输入用户名:")
    pwd = input("请输入登陆密码:")
    password = pwd.encode("utf8")
    s1 = md5()
    # 调用md5()里的update()方法
    s1.update(password)
    # 加密密码
    s1.hexdigest()
    # print(s1.hexdigest())
    login = mysqlhelper.MysqlHelper().one("select pwd from goods where name = %s", [name])

    if login == None:
        print('用户名错误')
        count += 1
        if count == 3:
            print("超出最大次数")
            break
    elif login[0] == pwd:
        print('登录成功')
        break
    else:
        print('密码错误')
        count += 1
        if count == 3:
            print("超出最大次数")
            break
    if login == None:
        print('用户名错误')
        count += 1
        if count == 3:
            print("超出最大次数")
            break
    else:
        if login[0] == pwd:
            print('登录成功')
            break
        else:
            print('密码错误')
            count += 1
            if count == 3:
                print("超出最大次数")
                break

 查询多条数据:

sql = "insert into user(id,name,addr) values(%s,%s,%s)"
listV = [(0, 'a', 'zhengzhou'), (0, 'b', 'hangzhou'), (0, 'c', 'lanzhou'), (0, 'd', 'shanghai'),
         (0, 'e', 'beijing')]
cur.executemany(sql, listV)
con.commit()提交事务
ORM操作数据库mysql:
# 1.导入模块 2.建立连接
from sqlalchemy import create_engine
engine = create_engine("mysql+mysqlconnector://root:123456@localhost/qiku")

# 3.创建会话实例
from sqlalchemy.orm import sessionmaker
session = sessionmaker(bind=engine)()

# 4.创建和表对应的对象
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String
base = declarative_base()


class Stu(base):
    __tablename__ = "stu"
    id = Column(Integer, primary_key=True)
    name = Column(String)

# 查询所有数据并且遍历
all = session.query(Stu.id, Stu.name).all()

# 得到所有行列
# for i in all:
#     print(list(i)[0], list(i)[1])

# 指定列
# n1 = int(input("请输入查询列:"))
# for i in all:
#     print(list(i)[n1])

# 查询第一条数据
# print(session.query(Stu.id, Stu.name).first())

# 查询指定行数据
# try:
#     n2 = int(input("请输入查询id:"))
#     result = session.query(Stu).filter(Stu.id == n2).first()
#     print("编号id:%s, 姓名name:%s" % (result.id, result.name))
# except Exception as e:
#     print(e)

# 添加一条数据
# session.add(Stu(id = 0, name = "c"))
# 添加多条数据
# session.add_all([Stu(id=0, name="c"), Stu(id=0, name="c")])
# session.commit()

# 删除数据
# n3 = int(input("请输入删除的id:"))
# session.query(Stu).filter(Stu.id == n3).delete()
# session.commit()

# 修改数据
# n4 = int(input("请输入修改的id:"))
# session.query(Stu).filter(Stu.id == n4).update({Stu.name: "aa"})
# session.commit()

 MD5加密:

pwd = input("请输入登陆密码:")
password = pwd.encode("utf8")
s1 = md5()
# 加密
s1.update(password)
# 解密密码
s1.hexdigest()

猜你喜欢

转载自blog.csdn.net/qq_42664045/article/details/86555001