python 数据库操作以及类方法

那么什么是数据库?

      通俗点讲就是存储数据的仓库,想用什么东西就可以在数据库中提取

1.讲数据拼接成字符串str

2.list

3.tuple

4.dict

以上其实属于同一种方式即将数据存储到内存当中

 

实际在开发过程当中,数据存储主要有三种形式

1.将数据存储到内存当中

①使用方便②程序关闭的时候,内存会被释放数据会丢失

2.将数据写入到文件当中

①数据存储是永久性的,不易丢失②打开关闭文件,操作数据库比较麻烦

3.将数据存储到数据库当中

①数据存储为永久性的,操作也比较方便②数据库学习难度比较大

数据库按照性质分为两大类:

1.关系型数据库:数据和数据之间存在着广泛的联系   比如:MySQL sqlite

   可以通过一个数据访问到数据的数据

2.非关系型数据库:数据和数据之间没有联系   比如:MongoDB Redis

①数据为单独的对数据之间的耦合度比较低,对数据进行增删改查不会影响其他数据

按照数据库规模大小来说分为四种:

1.大型数据库:oracle

2.中型数据库:SQLserver

3.小型数据库:mySQL

4.微型数据库:sqlite  大小大概只有4兆左右

下面开始数据库的一些具体操作

#引入数据库包
import sqlite3
#database : 数据库
#连接到一个数据库  有则打开,无则创建
connect = sqlite3.connect('myDB')
#设置数据库光标  光标是用来执行数据库命令的
cursor = connect.cursor()

#创建数据库表
#execute:执行
cursor.execute('create table if not exists my_info(name text,age int,des text)')
connect=connect.cursor()

#一个项目里面可能用到多个数据库,一个数据库里面有多张表
#对数据库进行增删改查操作

#添加
cursor.execute('insert into my_info(name,age,des) values ('小陈',20,'帅气潇洒又飘逸')')
cursor.execute('insert into my_info(name,age,des) values ('小火华',23,'清新有型清爽帅气')')
#修改
cursor.execute('update my_info set name="陈烨" where name="小陈"')
connect.commit()
#/删除数据
cursor.execute('delete from my_info where name="小陈"')
connect.commit()
#删除表中所有数据
cursor.execute('delete from my_info')
connect.commit()

#查询数据
cursor.execute('select * from my_info')#查询全部数据库中的信息

cursor.execute('select * from my_info where name = "小火华"') #查询指定的某一条数据
#fetch :抓取  one:一个
result  = cursor.fetchone()
#抓取所有的信息
#result  = cursor.fetchall()
#抓取两条信息
#result  = cursor.fetchmany(2)
print(result)

类方法

class People(object):
    def __instanceFun(self):
        print('我是一个实例方法')
    @classmethod
    def claddFun(cls):
        print('我是一个类方法')
    @staticmethod
    def staticFun():
        print('我是一个静态方法')
p=People()

#对象方法也叫做实例方法


class People(object):
    # 实例方法 在创建的时候需要一个self参数
    # 表示调用该方法的对象是谁
    def instanceFun(self):
        print('我是一个实例方法')
        # 类方法 在创建的时候需要一个cls参数
        # 表示调用该方法的类是谁
    @classmethod
    def classFun(cls):
        print('我是一个类方法')
        # 静态方法 无需指定调用的对象  因此方法后面不需要指定参数
        # 类可以通过类名/对象名+方法名字  的方式来调用
    @staticmethod
    def staticFun():
        print('我是一个静态方法')
    # 实例方法 ,类方法和静态方法的使用场景
    # 如果想让方法根据调用的对象的不同,显示不同的内容或者实现不同的功能经常使用对象方法
    # 如果方法不需要上诉操作,方法不需要调用的对象的不同,做出不同的调整经常使用类方法和静态方法
    # 静态方法可以被对象方法和类方法替换

        #创建一个实例对象
# 对象方法也叫作实例方法
p=People()
p.instanceFun()
People.classFun()
#静态方法可以通过类名/对象 + 方法的名称来调用
People.staticFun()
p.staticFun()

作业1:

新建一个数据库,里面有一个数据表
1.要求有这些字段
  手机牌子
  手机价格
  手机进货日期
  手机内存
  手机功能(yuele ,)
  手机存货量
2.可以根据手机的任意属性查询当前手机的存货量,
  如果手机数量不足,提示进货
3.

  新建一个对象,顾客 
  新建一个对象,售货员,售货员必须有部分手机存量为0
  顾客有一个属性,叫做需求,消费能力
  售货员根据顾客需求,在数据库中查找相应的手机
  并将所有结果返回给顾客,如果找不到指定手机则提示

import sqlite3
import random
con = sqlite3.connect('phoneDB')
cursor = con.cursor()
cursor.execute('CREATE TABLE IF NOT EXISTS phone_info(brand text ,price int,memory text,function text,count int) ')
con.commit()

class Customer(object):
    brand = ''
    memory = ''
    price = ''
    count = ''
    function = ''
class Seller(object):
    @classmethod
    def fullMyshop(cls):
        nameList = ['华为','小米8','oppo','vivo','锤子','一加']
        memoryList = ['512M','1G','2G','4G','8G']
        priceList = [599,799,999,1299,1499,1799,1999,2199,2599,2999,3599,3999,4599,4999,5999,6999]
        functionList = ['美颜手机','双卡双待','超长续航','高清音质','超性价比','娱乐专享','娱乐定制']

        for x in range(20):
            cursor.execute('INSERT INTO phone_info(brand,price,memory,function,count)' 'VALUES ("{}","{}","{}","{}","{}")'.format(random.choice(nameList),random.choice(priceList),random.choice(memoryList),random.choice(functionList),random.randint(0,10)))
        con.commit()
    @classmethod
    def findPhone(cls,other):
        cursor.execute('SELECT * from phone_info WHERE brand="{}" and price<="{}" and count >0'.format(other.brand,other.price,other.count))
        con.commit()
        print(cursor.fetchall())
Seller.fullMyshop()


Customer.brand='华为'
Customer.price = 2500
Seller.findPhone(Customer)

作业2.:创建学生信息管理系统

在控制台输入信息,程序执行不同命令:
控制台输入1:添加学生信息,学生所有信息需要通过控制台输入
控制台输入2:修改学生信息,需要在控制台指明哪个学生的信息需要修改,同时在控制台输入修改的内容
控制台输入3:删除学生信息,需要在控制台指明哪个学生需要被删除
控制台输入4:查询所有学生信息 
控制台输入其他数字:退出查询系统

第一种数据库方式:

import sqlite3
con = sqlite3.connect('studentDB')
cursor = con.cursor()
# input()
cursor.execute('CREATE TABLE if NOT EXISTS student_info(s_id text,name text,age text,sex text,class text)')
while True:
    print('-----学生信息管理系统-----\n''1----------插入学生信息\n' '2----------修改学生信息\n''3----------删除学生信息\n' '4----------查询学生所有信息\n' '5----------退出系统\n')
    number = input('请输入你的数字')
    if number == '1':
        student=input('请输入学生的信息学号,姓名,年龄,性别,班级')
        list = student.split(',')
        con = sqlite3.connect('studentDB')
        cursor = con.cursor()
        cursor.execute('INSERT INTO student_info(s_id, name, age, sex, class) VALUES ("{}","{}","{}","{}","{}")'.format(list[0],list[1],list[2],list[3],list[4]))
        con.commit()
        cursor.close()
        con.close()
    if number == '2':
         name1 = input('请输入要修改学生的姓名')
         student = input('请输入学生修改后的信息学号,姓名,年龄,性别,班级')
         list = student.split(',')
         con = sqlite3.connect('studentDB')
         cursor = con.cursor()
         cursor.execute('UPDATE student_info SET s_id = "{}", name = "{}", age = "{}", sex = "{}", class = "{}"  WHERE  name ="{}"'.format(list[0],list[1],list[2],list[3],list[4],name1))
         con.commit()
         cursor.close()
         con.close()

    if number == '3':
         name1 = input('请输入要删除学生的姓名')
         con = sqlite3.connect('studentDB')
         cursor = con.cursor()
         cursor.execute('DELETE FROM student_info WHERE name= "{}"'.format(name1))
         con.commit()
         cursor.close()
         con.close()
         cursor.execute('SELECT *FROM student_info')
         result = cursor.fetchall()
         print(result)
    if number == '4':
        con = sqlite3.connect('studentDB')
        cursor = con.cursor()
        cursor.execute('SELECT *FROM student_info')
        result = cursor.fetchall()
        print(result)
        cursor.close()
        con.close()
    if number == '5':
         print('退出系统')
         break

第二种方法:

def showInfo():
    print("-" * 30)
    print("     学生管理系统  v1.0")
    print(" 1.添加学生的信息")
    print(" 2.删除学生的信息")
    print(" 3.修改学生的信息")
    print(" 4.查询学生的信息")
    print(" 5.遍历所有学生的信息")
    print(" 6.退出系统")
    print('-' * 30)


# 定义一个列表,用来存储多个学生的信息
students = []

while True:
    # 把功能列表进行显示给用户
    showInfo()

    # 提示用户选择功能
    # 获取用户选择的功能
    key = int(input("请选择功能(序号):"))

    # 根据用户选择,完成相应功能
    if key == 1:
        print("您选择了添加学生信息功能")
        name = input("请输入学生姓名:")
        stuId = input("请输入学生学号(学号不可重复):")
        age = input("请输入学生年龄:")

        # 验证学号是否唯一
        i = 0
        leap = 0
        for temp in students:
            if temp['id'] == stuId:
                leap = 1
                break
            else:
                i = i + 1
        if leap == 1:
            print("输入学生学号重复,添加失败!")
            break
        else:
            # 定义一个字典,存放单个学生信息
            stuInfo = {}
            stuInfo['name'] = name
            stuInfo['id'] = stuId
            stuInfo['age'] = age

            # 单个学生信息放入列表
            students.append(stuInfo)
            print("添加成功!")

    elif key == 2:
        print("您选择了删除学生功能")
        delId = input("请输入要删除的学生学号:")
        # i记录要删除的下标,leap为标志位,如果找到leap=1,否则为0
        i = 0
        leap = 0
        for temp in students:
            if temp['id'] == delId:
                leap = 1
                break
            else:
                i = i + 1
        if leap == 0:
            print("没有此学生学号,删除失败!")
        else:
            del students[i]
            print("删除成功!")


    elif key == 3:
        print("您选择了修改学生信息功能")
        alterId = input("请输入你要修改学生的学号:")
        # 检测是否有此学号,然后进行修改信息
        i = 0
        leap = 0
        for temp in students:
            if temp['id'] == alterId:
                leap = 1
                break
            else:
                i = i + 1
        if leap == 1:
            while True:
                alterNum = int(input(" 1.修改学号\n 2.修改姓名 \n 3.修改年龄 \n 4.退出修改\n"))
                if alterNum == 1:
                    newId = input("输入更改后的学号:")
                    # 修改后的学号要验证是否唯一
                    i = 0
                    leap1 = 0
                    for temp1 in students:
                        if temp1['id'] == newId:
                            leap1 = 1
                            break
                        else:
                            i = i + 1
                    if leap1 == 1:
                        print("输入学号不可重复,修改失败!")
                    else:
                        temp['id'] = newId
                        print("学号修改成功")
                elif alterNum == 2:
                    newName = input("输入更改后的姓名:")
                    temp['name'] = newName
                    print("姓名修改成功")
                elif alterNum == 3:
                    newAge = input("输入更改后的年龄:")
                    temp['age'] = newAge
                    print("年龄修改成功")
                elif alterNum == 4:
                    break
                else:
                    print("输入错误请重新输入")
        else:
            print("没有此学号,修改失败!")
    elif key == 4:
        print("您选择了查询学生信息功能")
        searchID = input("请输入你要查询学生的学号:")
        # 验证是否有此学号
        i = 0
        leap = 0
        for temp in students:
            if temp['id'] == searchID:
                leap = 1
                break
            else:
                i = i + 1
        if leap == 0:
            print("没有此学生学号,查询失败!")
        else:
            print("找到此学生,信息如下:")
            print("学号:%s\n姓名:%s\n年龄:%s\n" % (temp['id'], temp['name'], temp['age']))
    elif key == 5:
        # 遍历并输出所有学生的信息
        print('*' * 20)
        print("接下来进行遍历所有的学生信息...")
        print("id      姓名         年龄")
        for temp in students:
            print("%s     %s     %s" % (temp['id'], temp['name'], temp['age']))
        print("*" * 20)
    elif key == 6:
        # 退出功能,尽量往不退出的方向引
        quitconfirm = input("亲,真的要退出么 (yes或者no)??~~(>_<)~~??")
        if quitconfirm == 'yes':
            print("欢迎使用本系统,谢谢")
            break;
    else:
        print("您输入有误,请重新输入")

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值