python mysql實例

商品數據增刪改查

1.進行用戶註冊登錄
2 連接數據庫
3. 建立遊標
4. 對數據庫進行操作
5. 關閉遊標
6. 關閉數據庫連接

from pymysql import connect


class JD(object):
    user_info = {}
    # 註冊
    def register(self):
        user_name = input("請輸入用戶名:")
        password = input("請輸入密碼:")
        if user_name in self.user_info.keys():
            print("該用戶已註冊,請登錄")
            self.login()
        else:
            self.user_info[user_name] = password
            print("%s註冊成功" % user_name)
            full_info = user_name + "" + password
            fp = open('info.txt', 'a+')
            fp.write(full_info + "\n")
            fp.close()
            x = input("是否使用新用戶名登陸?登陸輸入1,退出輸入q或者Q")
            if x == "1":
                self.login()
            else:
                print("退出,謝謝使用")
                return

    # 登錄
    def login(self):
        username = input("請輸入用戶名:")
        password = input("請輸入密碼:")
        if username in self.user_info.keys():
            if password == self.user_info[username]:
                print("登陸成功")
                self.run()
            else:
                print("密碼輸入錯誤")

    # 退出
    @staticmethod
    def exitp():
        print("退出程序")
        return

        # 初始化

    def __init__(self):

        # 創建connection對象
        self.conn = connect(host='localhost', port=3306, user='root', password='mysql', database='jing_dong',charset='utf8')
        # 獲取cursor對象
        self.cursor = self.conn.cursor()

    def __del__(self):
        # 關閉遊標對象
        self.cursor.close()
        # 關閉連接對象
        self.conn.close()

    def execute_sql(self, sql):
        self.cursor.execute(sql)
        for temp in self.cursor.fetchall():
            print(temp)

    def find_all_goods(self):
        # 顯示所有商品
        sql = "select * from goods;"
        self.execute_sql(sql)

    def find_goods_cate(self):
        sql = "select name from goods_cates;"
        self.execute_sql(sql)

    def find_goods_brands(self):
        sql = "select name from goods_brands;"
        self.execute_sql(sql)

    @staticmethod
    def print_menu():
        print("查詢所有商品信息請按1")
        print("查詢商品分類信息請按2")
        print("查詢商品商標信息請按3")
        #  print("查詢所有商品信息請按4")
        return input("請輸入要操作的編號:")

    def run(self):
        while True:
            opt = self.print_menu()
            if opt == "1":
                self.find_all_goods()
            elif opt == "2":
                self.find_goods_cate()
            elif opt == "3":
                self.find_goods_brands()
            else:
                print("輸入有誤,請重新輸入")


def main():
        jd = JD()
        jd.register()


if __name__ == "__main__":
    main()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章