冇基础写Python系列,这里会记录我写Python的所有过程,希望这个系列,它能给我和你都带来一份宝贵的经验。本系列所写的代码均是Python3版本。
1 数据库入门:
作为一个程序员,其实我们开发程序的实质就是操作各种各样的数据传给不同需求的用户。而在数据传递过程,我们需要一个仓库来保存(或提供)源数据,这些数据经过程序,然后通过各种需求呈现给用户。在程序开发的专业术语中,这个仓库,我们称它为“数据库”。
数据库(Database)是按照数据结构来组织、存储和管理数据的建立在计算机存储设备上的仓库。分为关系型数据库和非关系型数据库,在这里我将关注的是实操,概念就略过了。
常用的数据库有:MySQL,Mongodb,Oracle,Redis,SQLite,SQL Server等,对于初学者来讲,我们先需要循序渐进的掌握,不能一口吃一个胖子,这里(本文)将从最简单的适合小白入手的SQLite着手,其实数据库操作的原理是一致的,我们掌握了一种后普适性也是很大的,稍加调整就可以扩展到其他数据库,所以把sqlite练好之后再学其他数据库会简单很多。
2 数据库操作7不曲:
创建、插入、读取、更新、查询、排序、删除 (掌握这7步,你的数据库知识将初步够用了)
3 Python连接数据库流程
4 Python数据库7步曲
4.1 准备工作:连接(创建)数据库
SQLite3 可使用 sqlite3 模块与 Python 进行集成,所以我们要使用SQLite只需要import sqlite3并创建一个connection连接数据库,以便之后的七步曲操作。
import sqlite3 #导入sqlite数据库
def connet_db():
conn=sqlite3.connect('database.db')
# 连接到数据库,如果数据库不存在,那它就会被创建,并返回一个数据库对象
return conn
conn=connet_db() #执行数据库创建
4.2 创建数据表 create table
import sqlite3
def connet_db():
conn=sqlite3.connect('database.db')
# 连接到数据库,如果数据库不存在,那它就会被创建,并返回一个数据库对象
return conn
def create_table(conn):
# 获取cursor
cursor=conn.cursor()
# 创建数据表student
cursor.execute('''
create table if not exists student
(id int primary key not null,
stuname char(50) not null,
age int not null,
address char(50));''')
print("Table create successfully")
conn.commit() #一定要commit,不然上面的创建数据表的语句就白写了
conn.close() #执行完成之后养成关闭数据库连接的好习惯
conn=connet_db()
create_table(conn)
4.3 插入数据 insert
def insert_data(conn):
cursor=conn.cursor()
# 拼凑插入语句
insertSql="""
insert into student (id,stuname,age,address) \
values (1,'firstpython',25,'USA');
"""
# 通过cursor来execute拼凑的sql语句
cursor.execute(insertSql)
conn.commit() #切记要commit提交我们的数据库插入操作
conn.close() #最后养成好习惯,关闭数据库
pass
conn=connet_db()
insert_data(conn)
4.4 查询数据 select
def select_data(conn):
cursor=conn.cursor()
# 拼凑sql语句 1 select * 查询所有数据
select_all="""
select * from student
"""
data_all=cursor.execute(select_all)
# 查看查询回来的数据 fetchall 全部数据,fetchone 一条数据 fetchmany(size) 指定条数的数据
print(data_all.fetchall())
# 带条件查询
select_address="""
select address from student where address='USA'
"""
data_addr=cursor.execute(select_address)
print(data_addr.fetchall())
conn.commit() #同样记得要commit哦
conn.close() #执行完,养成关闭数据库的好习惯
conn=connet_db()
#create_table(conn)
#insert_data(conn)
select_data(conn)
查询效果:
Tips:要注意的是,不同于之前的操作,我们查询完数据库之后会有返回的值,我们可以定义一个变量保存它,但是我们直接打印发现是连串看不懂的字符编码 <sqlite3.Cursor object at 0x0000016ABB5AA3B0> ,那是因为,我们查询出来的数据,想看到数据就必须借助fetchall()方法。
fetchone():得到结果集的下一行
fetchmany([size = cursor.arraysize]):得到结果集的下几行
fetchall():得到结果集中剩下的所有行
或者使用for循环依次获取查询出的每一个值:
运行结果:
4.5 更新数据 update
def update_data(conn):
cursor=conn.cursor()
update_sql="""
update student set address = 'China' where id =2
"""
# 执行更新数据,相信认真看了我之前代码的同学,
# 一定发现我连China大中国都拼错了,这怎么可以呢,必须改,那update 意义就来了
cursor.execute(update_sql)
conn.commit()
# 执行update后,sql会返回一个更新数据表的数量
update_totalnum=conn.total_changes
# print()只能打印str哦,遇到数值等其他类型都要转成str类型
print("update number :" + str(update_totalnum))
# 如果你要查看你更新之后的数据,那就还需要再执行一次select 语句
update_data=cursor.execute('select * from student where id=2')
print(update_data.fetchone())
conn.close()# 最后关闭数据库
conn=connet_db()
#create_table(conn)
#insert_data(conn)
#select_data(conn)
update_data(conn)
运行结果:
4.6 删除 delete
def delect_data(conn):
cursor=conn.cursor()
delect_sql="""
delete from student where id = 1;
"""
cursor.execute(delect_sql)
# delete 执行完毕返回的同样是数量,我们要查询修改之后的就要select
conn.commit()
print("delete num:"+str(conn.total_changes))
update_data = cursor.execute('select * from student ')
print(update_data.fetchall())
# 最后养成好习惯 关闭数据库
conn.close()
conn=connet_db()
#create_table(conn)
#insert_data(conn)
#select_data(conn)
#update_data(conn)
delect_data(conn)
运行结果:
4.7 排序数据
这部分留给思考,知道了原理之后,相信只要sql语句写对了,很快就可以执行出来,排序的关键词是查 order by ** desc。
如:select * from student order by id desc
总结:
数据库,现在使用的数据库的基本操作无外乎这个7步,理解清楚了马上就可以从sqlite转成其他数据库如mysql,那么我们操作数据库到底要怎么做呢?
1 impoer 数据库(或数据库的驱动,里面会有各类型数据的connection)
2 创建数据库连接 connection
conn=数据库类型(数据库驱动).connect('建立的数据库')
3 获取cursor来执行数据库增删改查等命令
cursor=conn.cursor()
4 拼凑sql语句(增删改查排序等)
sql=“select insert update delete order by et.”
5 通过cursor执行sql操作
cursor.execute(sql) #不同操作会返回不同的结果 select 返回查询结果 update delete返回执行的数量
6 conn.commit() #执行以上的操作,不然白忙了
7 养成好习惯数据库
conn.close()
这个就是操作数据库要掌握的流程了。牢记在心,养成习惯。如果你需要上述源码,或者联系我,加下方微信哦。