SQLite数据库(一) 数据库概念 语法

来源:互联网 发布:老布的淘宝店 编辑:程序博客网 时间:2024/05/18 01:54

数据库:存储数据的仓库,每一个数据可都可以存在多张数据表
数据表:具体存储数据的表,类似excel表格
常见的数据库:MS SQL MySQL Oracle
SQLite 并不是数据库服务器软件,在开发中,它表现为某一个文件
查看SQLite 数据文件的软件:SQLiteSpy SQLiteExpert

创建数据库:
方法一:调用openOrCreateDatabase(String, int, CursorFactory)即可

创建数据表:
create table ‘表名’(设计字段列表);
字段列表的格式为:字段(列)名,数据类型,约束
多个字段之间使用逗号进行分隔
创建数据表示例(一):
String sql=”CREATE TABLE ‘student’(“+
“_id integer primary key autoincrement,”+”
stu_name varchar(16) not null unique,”+
“stu_phone_number varchar(16) not null unique”+
“)”;
(二):
String sql=crate table gongsi (id interger primary key autoincrement, name varchar(16) not null unique, bumen varchar(16) not null, age integer);

注意:SQLite 是非常轻量级的数据库,所以,SQLite 对存储的数据类型要求是不严格的,但是,依然推荐规范的使用SQLite 数据库。

数据操作:增删改查
增:insert into ‘表名’(字段列表)values(值列表)
字段列表和值列表中,各字段或值之间使用逗号分隔
删:delete from ‘表名’ where 字句
改:update ‘表名’ set 字段=值的赋值列表 where字句
查:select 字段列表 from ‘表名’where 子句 排序 分页

使用SQLiteDatabase 实现数据管理
【增加数据】insert()
第一个参数:表名
第二个参数:无视,当确保第三个参数为有效值时,第二哥参数没有任何意义
第三个参数:确保要增加的数据,第三个参数ContentValues 对象必须至少调用过1次put方法,即可使得该参数是有效的
返回值:新记录的ID,如果增加失败,则返回-1;(如果新增加的_id为8,则返回值为8,增加失败,则值为-1)
示例:
insert into gongsi (name, class, age) values (”老苏’, ‘yanfabu’, 38)
insert into gongsi (age, name, class) values (37, ‘老赵’, ‘yanfabu’)

【删除数据】delete();
第一个参数:表名
第二个参数:where 子句,其中各字段对应的值(例如:_id=1),可以使用问好(?)表示,如果使用问好,则对应的值需要在第三个参数中体现
第三个参数:第二个参数中各问号对应的值,如果第二个参数中没有问号,则第三个参数为null
返回值:受影响的行数,即删除的条目数量(如果删除5行,则值为5);

示例:
delete from gongsi // 慎用!!!(删除整张表)
delete from gongsi where id=3 (删除id=3的行)
delete from gongsi where bumen=’yanfabu’(删除所有部门是研发部的行)
delete from gongsi where id=3 and bumen=’yanfabu’ (删除id=3并且部门是研发部的)

【修改数据】update
语法:
update 表名 set 字段赋值列表 [where子句]
字段赋值列表:
字段名=值
多个字段赋值语法之间使用逗号分隔
示例:
update gongsi set bumen=’yanfabu’ // 慎用
update gongsi set bumen=’yanfa bu’, age=26 where id=3

【查询数据】
语法:
select 字段列表 from 表名 [where子句] [order by子句] [limit子句]
示例:
select id, name, bumen from yanfabu
select id, name, bumen, age from yanfabu
select * from yanfabu
select id, name, bumen from yanfabu where id>3
select id, name, bumen from yanfabu where id=1 or id=7
select id, name, bumen, age from yanfabu order by age
select id, name, bumen, age from yanfabu order by age desc
select id, name, bumen from yanfabu where id>3 order by age desc
select id, name, bumen from yanfabu limit 0, 3
order by子句:
字段名称 [asc/desc] [,字段名称 [asc/desc]]
其中,asc表示顺序,desc表示倒序
limit子句(在MS SQL Server中不适用):
limit 偏移量, 数据量

0 0
原创粉丝点击