在SQLlite数据库中往往一个数据文件就是一个schema,但是在平时的业务或者是一些条件中可能是不同的内容存放在不同的schema中,即不同的数据文件,有的场景下需要数据关联时就可以使用SQLlite的数据附加来建立一个临时的链接。如下,在使用my_test的schema时需要关联查询一个为my_test2的schema就可以使用附加:
[root@localhost data]
# sqlite3 my_test.db #在SQLlite数据库中缺省database名为main
SQLite version 3.6.20
Enter
".help"
for
instructions
Enter SQL statements terminated with a
";"
sqlite> .database
seq
name
file
--- --------------- ----------------------------------------------------------
0 main
/data/my_test
.db
sqlite> ATTACH DATABASE
'/data/my_test2.db'
As
'my_test2'
;
#在当前schema下附加上/data/my_test2.db中的数据,并且起一个别名为my_test2,当然也可以起其他的名字
sqlite> .databases
seq
name
file
--- --------------- ----------------------------------------------------------
0 main
/data/my_test
.db
2 my_test2
/data/my_test2
.db
sqlite> CREATE TABLE my_test2.test_attach (
...> a int(10),
...> b int(10)
...> );
sqlite> SELECT * FROM my_test2.sqlite_master WHERE
type
=
'table'
AND tbl_name =
'test_attach'
;
#直接在当前schema下使用/data/my_test2.db中的数据,并且查看
table|test_attach|test_attach|4|CREATE TABLE test_attach (
a int(10),
b int(10)
)
sqlite> .
exit
[root@localhost data]
# sqlite3 /data/my_test2.db #切换成my_test2.db的schema查看验证下
SQLite version 3.6.20
Enter
".help"
for
instructions
Enter SQL statements terminated with a
";"
sqlite> SELECT sql FROM sqlite_master WHERE
type
=
'table'
AND tbl_name =
'test_attach'
;
CREATE TABLE test_attach (
a int(10),
b int(10)
)
如此就是在SQLlite数据库中的附加数据库,它其实是一个链接,用于在不同的数据schma数据文件下使用其他的schma数据文件,在这里需要注意的是目前在SQLlite数据库中附加是临时的,在当前session中创建一个链接,如果在退出这个session后附加就自动分离:
[root@localhost data]
# sqlite3 /data/my_test.db
SQLite version 3.6.20
Enter
".help"
for
instructions
Enter SQL statements terminated with a
";"
sqlite> .database
seq
name
file
--- --------------- ----------------------------------------------------------
0 main
/data/my_test
.db
当然有如果有附件数据库那一定有分离,分离就比较简单:
sqlite> .databases
seq
name
file
--- --------------- ----------------------------------------------------------
0 main
/data/my_test
.db
2 my_test2
/data/my_test2
.db
sqlite> DETACH DATABASE
"my_test2"
;
sqlite> .databases
seq
name
file
--- --------------- ----------------------------------------------------------
0 main
/data/my_test
.db
这样就成功的主动分离附加在当前schma下的其他数据文件,在这里要特别注意的是如果分离的数据库是在内存或临时空间内,分离后会销毁其分离的数据。