python-数据库

数据库

SQLite,是一款轻型的数据库,是遵守ACID的关系型数据库管理系统,

原子性(Atomicity)、 一致性(Consistency)、

隔离性(Isolation)、 持久性(Durability)

它的设计目标是嵌入式的,而且已经在很多嵌入式产品中使用了它, 它占用资源非常的低,它能够支持Windows/Linux/Unix等等主流的操作系 统, 同时能够跟很多程序语言相结合。

SQL 结构化查询语言 ==》数据库脚本语言

sqlite3 下载地址:

https://www.sqlite.org/download.html

win选择:

sqlite-dll-win64-x64-3320300.zip

sqlite-tools-win32-x86-3320300.zip

Mac选择:

sqlite-tools-osx-x86-3320300.zip

安装过程:

1、首先将下载的两个压缩包解压在同一个目录下,例如 D:\SQLite;

2、将该路径添加到系统的Path环境变量里;

3、在cmd中输入sqlite3 --version,若显示版本号,则安装成功;

4、退出系统用 .quit

存储类型:

NULL NULL值(不是空值)

INTEGER 带符号的整数

REAL 浮点值(8字节)

TEXT 文本字符串(UTF-8,UTF-16BE,UTF-16LE)

BLOB BLOB数据类型

(Sqlite 没有单独的Boolean类型,在数据库中存储为整数0(false), 1(true))

(Sqlite 没有单独的Date类,存储时会变成TEXT,INTEGER,REAL类型)

DOS命令:

D:\ dir 查看目录下的文件信息

D:\ cls 清理屏幕显示

D:\ cd C:\Users\Administrator\Desktop\pythonCode\07 进入到目标代 码目录

D:\sqlite3 回车 命令行会自动进入该目录下

sqlite> 表示正常进入到dbms系统中

退出系统用 .quit

先有数据库 ==》创建数据表 ==》增加数据 ==》维护(增加,删除, 修改,查询)

基本操作:

1、创建数据库文件并登录;

Sqlite3 test.db ===》.db 后缀的是数据库文件,其中允许创建多个表 格。

手工创建 xxx.db 也可以,只要保证文件后缀是 .db 即可。

2、在数据库中新建表; SQL 语句

create table user (id int ,name text,pass text);

create table test (id integer primary key autoincrement not null,name text);

id integer primary key autoincrement not null

整形 主键 自动增长 非空

create table test(id int , name text, pass text);

注意:表名 可以自由定义,表的字段名称也可以自由定义 但是类型要正 确。

如果出现 syntax error 表示SQL 语句有语法错误。

.tables 查看创建的表是否成功

以下操作都是基于SQL 语句执行,与平台无关都可以正常执行。

3、向数据库中插入一条记录:

insert into test (name) values (''OpenLab"); #指定值插入

inser into 是插入关键字

test 是表名称

name是表中的列名称

values是关键字

"OpenLab"是插入的列对应的数据值。

insert into test(id,name,pass) values (1, 'zhang', '123345'); #全列匹 配插入

insert into test values (2, 'asd"','2345'); #全列默认匹配插入,必须值 一一匹配

insert into test (id,name) values (3, 'afasdf'); #指定值插入

4、查询所有表中数据:

select * from test; #查询所有表中记录并打印输出

select 是查询关键字

* 是通配符,表示所有列都输出

from 是关键字

test 是表名字

select * from test where id = 1; # where 辅助查询关键字,限定范 围

select * from test where pass = 123 and name = "张三";

select * from test where id = 1 or id = 2;

select * from test where id > 1;

select id,name from test; #指定列的时候可以间隔列名

select id,name from test where id = 1 ; #列名和限定词一起组合查询

思考题: 首先创建一个数据库并设计相关的表,然后

Sqlite3 test.db

create table test(id int , name text, pass text);

insert into test(id,name,pass) values (1, "zhang" , "123345");

create table stu(id int ,name text,score real);

insert into stu(id,name,score) values (1, "wangwu" ,99.9);

1、编写一条sql语句可以在数据库表中找到指定用户的密码信息。

select pass from test where name = "xxx";

2、编写一条sql语句可以在数据库表中查询成绩是60分上的学生学号 信息。

select id from stu where score >= 60;

5、修改指定表中数据

update test set name = 'caoqb' ; #会修改表中所有记录,慎用

update 是修改关键字

test 是修改的表名字

set 是设置关键字

name 是列名字

= "xxx" 是修改后的值

update test set name = "xxx" where id = 5;

update test set name = "xxx" , pass = "yyy" where id = 3;

update test set name = "xxx" where id >1 and pass = 2345;

6、删除表中指定数据:

delete from test where id = 1;

delete from 是删除关键字

test 是要删除信息的表名字

where 限定词

id=1 限定条件

delete from test where id >1 and pass = 2345;

delete from test where id =1 or id = 2;

delete from test ; ///删除表test中所有数据,直接删除无法恢复。慎用

7、退出数据库

以下不属于sql语句,属于数据库sqltie3自己的命令

.exit .q

7.1 .tables //显示当前数据库的表格

7.2 .schema tablename; //显示表格结构

7.3 .help #显示DBMS中所有相关的内部指令

练习题:

使用以上常规操作命令在各自机器上搭建操作环境 完成基本的增加 删除 修改 查询 功能sql语句同时 考虑如何将以上操作能简化处理 ?

==》可视化 ==》sqlite administor

http://sqliteadmin.orbmu2k.de/

其他的数据库操作:

1、 删除表

drop table test1;

2、 排序 默认是 ASC:升序,DESC:降序 不区分大小写

select * from test where price < 103 order by price desc limit 5 ;

order by xxx 按照xxx所在的列排序

limit num 只需要查询指定的前num个数据

3、去重

select distinct name from test;

4、分组 GROUP BY 子句必须放在 WHERE 子句中的条件之后,必须放在ORDER BY 子句之前。

select * from test where price > 102

group by name having count(name) < 2

order by name limit 4;

5、模糊查询

WHERE SALARY LIKE '200%' 查找以 200 开头的任意值

WHERE SALARY LIKE '%200%' 查找任意位置包含 200 的任意值

WHERE SALARY LIKE '_00%' 查找第二位和第三位为 00 的任意值

WHERE SALARY LIKE '2_%_%' 查找以 2 开头,且长度至少为 3 个字 符的任意值

WHERE SALARY LIKE '%2' 查找以 2 结尾的任意值

WHERE SALARY LIKE '_2%3' 查找第二位为 2,且以 3 结尾的任意 值

WHERE SALARY LIKE '2___3' 查找长度为 5 位数,且以 2 开头以 3结尾的任意值

_ 是一个占位符, %是任意长度占位 。

6、where 子句:

and : 在where中可以连接多个条件

sqlite> select * from test where age > 13 and price >= 105;

or : 或

sqlite> select * from test where age > 13 or price < 200;

not != : 否定,一般和not in / not between 等合用

select * from test where name != "aaa"

between : 在两个值之间进行搜索

sqlite> select * from test where age between 12 and 17;

not in : 和in相反

sqlite> select * from test where age not in (12,15);

in : 返回值等于匹配值的数据

sqlite> select * from test where age in (12,15);

like : 相似匹配,后面字符不检查用 % ,大小写不敏感

sqlite> select * from test where name glob 'y*';

sqlite> select * from test where name

like 'Y%'; glob : 相似匹配,后面字符不检查用 % ,大小写不敏感

sqlite> select * from test where name glob 'y*';

is null : 用于把某个值和NULL进行比对

sqlite> select * from test where name is null;

is : 类似于 =

is not : 类似于 !=

7、导入导出

导出命令:

sqlite3 data.db

>.output dd.sql 导出的数据库脚本名称为 dd.sql

>.dump 导出所有数据

>.q 退出数据库

另一种:

sqltie3 xxx.db .dump

> yyy.sql 在数据库尚未登录时候操作

> 符号在这里表示输出到某个 文件 删除原有的数据库

导入命令:

sqlite3 新数据库.db

>.read dd.sql

>.tables 查看导入效果

另一种:

sqlite3 xxx.db < xxx.sql

< 符号在这里表示从某个脚本导入文件内容

练习:

1、将创建数据库表的sql语句和 删除数据表内容的sql语句写成sql脚本并在数据库中执行,查看效果。

2、编写代码完成一个脚本文件的读写,并通过执行该脚本能向指定的数据库中依次添加100条不同记录的消息。

python 与 sqlite3 的接口:

1、首先需要导入模块:

import sqlite3

2、连接数据库(如果数据库不存在就会创建新的数据库)

con = sqlite3.connect("test.db")

3、创建游标

cur = con.cursor()

4、常规的增加 删除 修改 查询 等SQL操作

sql = "CREATE TABLE IF NOT EXISTS test(id INTEGER PRIMARY KEY,name TEXT,age INTEGER)" #组织SQL命令串

#str = "insert into user values (7, 'wo' , '8888');"

#str = "delete from user where id = 7;"

#str = "update user set pass = '123456' where id = 6;"

cur.execute(sql) #执行SQL命令串

查询:

cur.execute('SELECT * FROM user')

#print(cur.fetchone()) #取游标第一行数据形成元组

res = cur.fetchmany(3) #取多行指定数据形成列表

print(res) #结果是列表中存储的三行元组信息

res = cur.fetchall() #取表中所有数据记录

for line in res: #遍历所有的查询记录

print(line) #以元组形式输出所有select的结果数据

5、事务的提交和回滚 con.commit() #提交 正式生效到数据库文件

con.rollback() #回滚 撤销刚才的内存操作

6、断开会话连接,释放资源 cur.close() # 关闭游标

con.close() # 断开数据库连接

练习题:

根据以上流程编写数据库操作模块,可以将用户输入的信息,写入 到数据库表中。增加,修改,删除都是用户输入的数据而不是固定 值。

print("请输入要插入数据库的id,name,pass的数据")

id= input()

name=input()

pasd=input()

#1 字符串的拼装

str = "insert into user values ("+str(id)+" , '"+name+"' , '"+pasd+"');"

#2 用元组占位拼装

cur.execute("insert into user values (%d, '%s' , '%s');"% (id,name,pasd))

#3 用问号占位拼装

cur.execute("insert into user values (?,?,?);" ,(id,name,pasd))

注意:关于数据库句柄和游标还有如下属性说明

connect方法返回con对象,即是数据库链接对象,它提供了以下方法:

.cursor() 方法来创建一个游标对象

.commit() 方法来处理事务提交

.rollback() 方法来处理事务回滚

.close() 方法来关闭一个数据库连接

对数据库的查询需要使用到游标对象,首先通过cursor()创建一个游标对 象:

游标对象有以下方法支持数据库操作:

.execute() 用来执行sql语句

.executemany() 用来执行多条sql语句

.close() 用来关闭游标

.fetchone() 用来从结果中取一条记录,并将游标指向下一条记录

.fetchmany() 用来从结果中取多条记录。

.fetchall() 用来从结果中取出所以记录

.scroll() 用于游标滚动

相关推荐
databook7 小时前
Manim实现闪光轨迹特效
后端·python·动效
Juchecar8 小时前
解惑:NumPy 中 ndarray.ndim 到底是什么?
python
用户8356290780518 小时前
Python 删除 Excel 工作表中的空白行列
后端·python
Json_8 小时前
使用python-fastApi框架开发一个学校宿舍管理系统-前后端分离项目
后端·python·fastapi
数据智能老司机15 小时前
精通 Python 设计模式——分布式系统模式
python·设计模式·架构
数据智能老司机16 小时前
精通 Python 设计模式——并发与异步模式
python·设计模式·编程语言
数据智能老司机16 小时前
精通 Python 设计模式——测试模式
python·设计模式·架构
数据智能老司机16 小时前
精通 Python 设计模式——性能模式
python·设计模式·架构
c8i16 小时前
drf初步梳理
python·django
每日AI新事件16 小时前
python的异步函数
python