嵌入式sqlite3
一、sqlite3安装
1.本地安装
下载安装包,官网地址:http://www.sqlite.org/download.html
步骤如下:
$tar xvfz sqlite-autoconf-3071502.tar.gz $cd sqlite-autoconf-3071502 $./configure --prefix=/usr/local //指定安装目录 $make $make instal
2.在线安装
sudo apt-get install sqlite3
查看是否安装完成 sqlite3
在终端输入sqlite3是否显示如下内容:
SQLite version 3.11.0 2016-02-15 17:29:24
Enter ".help" for usage hints.
Connected to a transient in-memory database.
Use ".open FILENAME" to reopen on a persistent database.
sqlite>
使用中编译时出现: fatal error: sqlite3.h: 没有那个文件或目录
描述:找不到头文件
原因:系统没有安装函数库
解决办法:sudo apt-get install libsqlite3-dev
二、sqlite3数据库命令(重点)
1、系统命令,都以'.'开头
.exit
.quit
.table 查看表
.schema 查看表的结构
2、sql语句,都以‘;’结尾
1-- 创建一张表
create table stuinfo(id integer, name text, age integer, score float);
2-- 插入一条记录
insert into stuinfo values(1001, 'zhangsan', 18, 80);
insert into stuinfo (id, name, score) values(1002, 'lisi', 90);
3-- 查看数据库记录
select * from stuinfo;(*通配表示所有数据)
select name,score from stuinfo;
查询指定的字段
where表示选取,and表示与(同时满足),or表示或
select * from stuinfo where score = 80;
select * from stuinfo where score = 80 and name= 'zhangsan';
select * from stuinfo where score = 80 or name='wangwu'
select * from stuinfo where score >= 85 and score < 90;
4-- 删除一条记录
delete from stuinfo where id=1003 and name='zhangsan';
5-- 更新一条记录
update stuinfo set age=20 where id=1003;
update stuinfo set age=30, score = 82 where id=1003;
6-- 删除一张表
删除整张表而不是某一条记录与delete区分
drop table stuinfo;
7-- 增加一列
alter table stuinfo add column sex char;
8-- 删除一列
因sqlite没有直接删除一列的功能,所以分三步,先新建一个数据库复制原来的数据库(除去想要删除的那一列不复制)
然后删除原来的数据库,再把新建的数据库改名为原来的数据库,达到删除一列的目的。
create table stu as select id, name, score from stuinfo;
drop table stuinfo;
alter table stu rename to stuinfo;
数据库设置主键:
create table info(id integer primary key autoincrement, name vchar);
主键就是限制资料不重复的字段﹐设置为主键的字段(可多个字段一起做主键)﹐设了主键就限制了资料的唯一性。
例如在人事资料中有一个身份征号的字段﹐这个就可设为主键(因为身份征号不会重复),但姓名就 不可以,因为姓名可以重复。
另外设置了主键有利于提高数据的检索速度﹐也保证数据的准确性