园长

学无止境 知行合一

SQL基础语法

以下是简单的建表操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import sqlite3  #导入库
conn=sqlite3.connect('test1.db') #连接数据库
print('连接数据库成功')
c=conn.cursor() #获取游标
sql='''
create table compny
(id int primary key not null,
name text not null,
age int not null,
address char(50),
salary real
);
''' #sql语句
c.execute(sql) #获取游标
conn.commit() #提交数据库操作
conn.close() #关闭连接
print('成功建表')

以下则是查询操作,返回info为python数组对象

1
2
3
4
5
6
......
sql="select * from compy"
data=c.execyte(sql)
for info in data:
print(info)
....

执行结果

(0, ‘2’, 18, ‘zjjjjj’, 0.0)
(3, ‘2’, 210, ‘新疆’, 1.0)
(4, ‘2’, 20, ‘陕西’, 1.0)
(5, ‘2’, 20, ‘安徽’, 1.0)
(6, ‘2’, 20, ‘河南’, 1.0)


sql语句大小写不敏感

insert插入(增)

insert into 表名 values(值1,值…)

1
insert  into  compny  values(1'陕西省'400123123)

delete删除(删)

delete from 表名 where 字段名 = 值

1
delete  from  compny where  id = 1

update更新(改)

update 表名 set 字段名 = 新值 where 字段名 = 旧值

1
update  compny  set  address  =  "新疆"  where  address  =   "陕西"

select查询(查)

select 字段名 from 表名

此种查询只列出你所需要查询的字段,查询多个以 ,隔开

1
2

select id from compny

select * from 表名

查询出此表的所有字段

1
2

select * from compny

distinct关键字

select distinct 字段名 from 表名

给查询的结果去重

where条件语句

在末尾加 where 表示条件,例如:

select * from 表名 where 字段名 = 值

=, >, <, >=, <=, <>(不等于)都适用于where

and or运算符

and 和 or 可在 where 子语句中把两个或多个条件结合起来3

and:

select * from 表名 where 条件1 and 条件2

1
2
3

select * from compny
where id = 0 and address = "新疆"

select * from 表名 where 条件1 and 条件2

1
2
select * from compny
where id = 0 or address = "新疆"

in

where 字段名 in 值
where 字段名 in (值1,值2,值3….)

1
2
select * from compny
where id in(1,2)

between

select * from 表名 where 字段名 between 左范围 and 右范围

左右都为闭

1
2
select * from compny
where id between 0 and 2

limit规定返回数目

select * from 表名 limit 2

1
select  *  from  compny  limit  1

将只返回一条记录

orderby排序

1
2
3

select * from compny
order by id

将按照id排序

like与通配符排序

通配符 描述
% 代表零个或多个字符
_ 仅替代一个字符
[charlist] 字符列中的任何单一字符
[^charlist] 或者 [!charlist] 不在字符列中的任何单一字符

## %

adderss有“新”开始的记录

1
2
SELECT * FROM compny
WHERE address LIKE '新%'

id包含“1”的记录

1
2
SELECT * FROM compny
WHERE id LIKE '%1%'

## _

_ 代表一个字符

1
2
SELECT * FROM compny
WHERE number LIKE '400_1_1'

## sqlite3中[charlist]不能获取结果



 评论




博客内容遵循 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 协议

本站使用 volantis 作为主题 。