【Python】数据库(创建库 访问 连接 创建表 编辑记录 案例:客户管理实现)

文章目录

  • * 库表与管理
    • 1.访问数据库
      • 1.1 连接与创建数据库
      • 1.2 创建表
      • 1.3 编辑表记录
        • 1.3.1 添加记录
        • 1.3.2 修改记录
        • 1.3.3 返回所有记录
        • 1.3.4 删除记录
        • 1.3.5 查询记录
      • 1.4 案例:客户管理 SQLite 实现

* 库表与管理

1.访问数据库

SQLite 是 Python 自带的数据库管理模块(sqlite3)。不用额外安装

1.1 连接与创建数据库

连接=sqlite3.connent(数据库)
  • 如果数据库存在,访问并连接;

    如果不存在,自动创建并连接。

    import sqlite3cn=sqlite3.connect('cust.db') # cn是连接对象
    print(type(cn)) # type(对象)返回对象类型
    cn.close() # 关闭数据库
    

1.2 创建表

  • 访问表时,要把表转入内存的缓冲区,再对缓冲区的数据进行操作。

    因此,定义一个指向缓冲区的指针(即:游标),来访问缓冲区的数据。

  • 创建访问表的步骤:

    (1)创建数据库连接cn。

    (2)创建游标cur。

    (3)执行创建表语句。

import sqlite3cn=sqlite3.connect('cust.db') # 连接数据库
cur=cn.cursor() # 设置游标: 游标名=连接.cursor()
# 创建表的sql语句
sqls='create table cust(cid text(4),cname text(10),cage integer(2))'
cur.execute(sqls) # 游标.execute(sql) 在游标所指向的数据库中执行sql语句# 删除表
cur.execute('drop table cust')

1.3 编辑表记录

1.3.1 添加记录

  • 添加记录,可以添加整个记录;

    也可以添加部分内容(需声明属性及其值)。

游标.execute('insert into cust(cid,cname,cage) values("c002","tim",17)')
# 查看记录个数
游标.rowcount()
  • 添加记录可以使用参数?
  • 如果需要一次添加多个记录,则可以使用添加 cur.executemany()。
cur.executemany('insert into cust values(?,?,?)',[("c005","Mar",19), ("c006","Nar",20)])

1.3.2 修改记录

cur.execute('update cust set cage=20 where cid="c001"')
cn.rollback() # 撤销最后一次修改
cn.commit() # 必须把缓冲区的数据写回数据库,否则修改无效。

1.3.3 返回所有记录

记录集=cur.fetchall()
print(记录集)
rs=cur.fetchall()
print(rs)
# 运行结果:
[('c001', 'tom', 16), ('c002', 'tim', 17), ('c003', 'jim', None), ('c004', 'jon', 18), ('c005', 'Mar', 19), ('c006', 'Nar', 20)]

1.3.4 删除记录

游标.execute('delete from cust where cid="c003"')

1.3.5 查询记录

游标.execute('select cid,cname from cust where cid="c006"')返回一个记录:cur.fetckone()。
返回 n 个记录:cur.fetckmany([n])。n:返回记录的个数(默认:1)。
返回所有记录:cur.fetchall()

1.4 案例:客户管理 SQLite 实现

题目要求:使用 Python 和 sqlite3,实现如下迷你客户信息管理系统。
(1)具有添加、修改、删除、查询、显示客户和帮助信息等功能。
(2)菜单显示内容如下:
客户管理
========
1. 添加客户
2. 修改客户
3. 删除客户
4. 查询客户
5. 显示客户
6. 清空客户
7. 帮助信息
8. 退出系统
========
import sqlite3# 查找客户
def find(no): # 查找编号为no的客户cn=sqlite3.connect('Cust.db') # 连接数据库cur=cn.execute('select* from Cust where cno=?',(no,))# 在数据表中查询编号为no的客户Cust=cur.fetchall() # 返回所有符合条件的记录# n=1表示查找成功,=-1则没有编号为no的客户if len(Cust)>0:n=1else:n=-1cn.close()return n# 添加客户
def appe():cn=sqlite3.connect('Cust.db')cno=input('输入户号:')if cno=='':print('户号无效!')else:if find(cno)==1:print('户号已存在,重新添加!')else:cname=input('输入户名:')if cname=='':print('户名无效!')else:cn.execute('insert into Cust values(?,?)',(cno,cname))cn.commit() # 把缓冲区的数据写回数据库,否则修改无效。print('添加成功!')cn.close()# 修改客户
def alter():cn=sqlite3.connect('Cust.db')cno=input('输入户名:')if find(cno)==-1:print('查无此人!')else:print('原户号:%s'%cno)nid=input('输入新户号:')if nid=='':print('户号无效!')else:if find(nid)==1:print('客户存在!')else:cname=input('输入新户名:')if cname=='':print('户名无效!')else:cn.execute('update Cust set cno=?,cname=?where cno=?',(nid,cname,cno))cn.commit()print('修改成功!')cn.close()# 删除客户
def dele():cn=sqlite3.connect('Cust.db')cno=input('输入户号:')if find(cno)==-1:print('查无此人!')else:print('户号:%s'%cno)yn=input('确定删除(y/n)?')if yn=='y':cn.execute('delete from Cust where cno=?',(cno,))cn.commit()print('删除成功!')else:print('删除失败!')cn.close()# 查找客户
def seek():cn = sqlite3.connect('Cust.db')cno = input('输入户号:')if find(cno) == -1:print('查无此人!')else:cur = cn.execute('select * from Cust where cno=?', (cno,))tm = cur.fetchone()print('查询结果:')print('户号:%s' % tm[0])print('户名:%s' % tm[1])cn.close()# 显示所有客户
def disp():cn = sqlite3.connect('Cust.db')cur = cn.execute('select * from Cust')Cust = cur.fetchall()if len(Cust) == 0:print('没有客户!')else:print('客户信息:')n = 0print('\t ', '户号', '\t', '户名')for u in Cust:for a in u:print('\t ', a, end='')print()cn.close()# 删除客户
def delall():cn = sqlite3.connect('Cust.db')cn.execute('drop table if exists Cust')cn.execute('create table Cust(cno text primary key,cname text)')cn.close()print('客户已空!')# 帮助信息
def helpc():print('请按照菜单执行!')def crea():cn = sqlite3.connect('cust.db')  # 连接数据库cur = cn.cursor()  # 设置游标: 游标名=连接.cursor()# 创建表的sql语句sqls = 'create table cust(cno text(4),cname text(10))'cur.execute(sqls)  # 游标.execute(sql) 在游标所指向的数据库中执行sql语句print('创建成功!')# 主函数
while 1:print(' 客户管理')print('========')print('1. 添加客户')print('2. 修改客户')print('3. 删除客户')print('4. 查询客户')print('5. 显示客户')print('6. 清空客户')print('7. 帮助信息')print('8. 退出系统')print('9. 创建数据库和客户表')print('========')yn=input('选择输入(1,2,3,4,5,6,7,8):')if yn=='1':appe()elif yn=='2':alter()elif yn=='3':dele()elif yn=='4':seek()elif yn=='5':disp()elif yn=='6':delall()elif yn=='7':helpc()elif yn=='9':crea()else:print('谢谢使用,再见!')breakinput('回车继续...')

本文链接:https://my.lmcjl.com/post/2759.html

展开阅读全文

4 评论

留下您的评论.