db2 连接到远程数据库
第一步建一个结点:
>db2 catalog tcpip node 结点名 remote 数据库服务器IP地址 server 端口(50000)
第二步建一个到库的联结别名:
>db2 catalog db 库名 as 别名 at node 结点名
第三步建立联结:
>db2 connect to 别名 user 用户名 using 用户密码
断开联结:
db2 connect reset
如何备份:
>db2 backup db 数据库名 to 设备名(如:c:);
恢复:
>db2 restore db 数据库名 from 设备名
(回滚rollforward我不太清楚)
注释:rollforword 是前滚的意思,向前到某一个时间,以保持数据的一致性,用于在线备份后的恢复,恢复是从log日志中开始到日志中的某一个时间,即可。只有在数据一致性得到保证的情况下,才能继续对数据库操作。
连接到数据库时报回滚错误
用下面的命令:
db2 rollforward db fmisadd to end of logs and complete
导出库中表的数据:
>export to 文件名.ixf of ixf select * from 表名
>import from 文件名.ixf of ixf create into 表名
导出库的数据格式还有两种del(文件格式)和wsf,但ixf格式信息最全,包含表结构信息,可恢复出已删去的表。
sql的inner/left/right/full join,这些概念在<<数据库概论>>中有说明,left以左表为主,right以右表为主,full左右表记录都会在查寻结果中。
例如:>select aa,bb from db1 left join db2 on db1.id=db2.id
合并查寻:把两个或几个查寻结果合并到一个字段(条件是字段必须兼容)
格式:select ...... union select ....;
使用临时表:
with tmptable (字段1,...) as (select....) --建一个临时表
select 字段1,.... from tmptable,另一个表 where.... --使用该临时表于另一个表交叉查寻。
**order by 必需出现在结果集,在临时表中不能用。
截取字符串
substr(字段名,开始位置,字符个数)
判断是否是空
字段名 is null
例子:
到什么时候活了10000天:
select distinct date('1980-01-01')+10000 day from a
一共活了多少天:
select distinct days(current date)-days(date('1980-01-01')) from a
类型转换:用cast ,例:
select distinct cast(current date as char(10))||'aa' from a
case的使用:
select case when length(rtrim(学历))=0 then '未知学历' else xl end,rs from a
例:查寻一个公司的年龄分布:
with tmptable as (select case when year(current day)-csrq<20 then '小于20岁' when year(current day)-csrq<25 then '20-24岁' when year(current day)-csrq<30 then '25-29岁'
when year(current day)-csrq<35 then '30-34岁'
when year(current day)-csrq<40 then '35-39岁'
when year(current day)-csrq<45 then '40-44岁'
when year(current day)-csrq<50 then '45-49岁' else '大于50岁' end
as x from a)
select x,count(*) from tmptable group by x;
一个数据库中有些系统建的表是用来保存该库各种信息的,如:syscat.tables
例:查有多少个userid的表:
select count(*) from syscat.tables where type='T' and tabschema='uerid'
例:产生一个备分库中所有表的文本:
select 'export to '|| tabname || '.ixf of ixf select * from userid.' ||tabname||';' from syscat.tables where type='T' and tabschema='userid';
得到该instance的各种参数:(dbm cfg是整个DB2的参数,db cfg是对某个数据库的参数)
>db2 get dbm cfg
>db2 get db cfg for 数据库名
修改参数:
>db2 update dbm cfg using 参数 你要的数
>db2 update db cfg for 数据库名 using 参数 你要的数
当第一个用户连结到该数据库时会申请一个内存缓冲,默认是250页每页4k即1M。
Buffer pool size<4K> [BUFFPAGE]=250
修改该值:
>db2 update db cfg for test using buffpage 你要的数
但它的有效还取决于syscat.bufferpools中的npages是否为-1,为-1时它才有效,否则以syscat.bufferpols中的npage为准。
可用下面的命令看:
>select * from syscat.bufferpools
一般此值的设置应为系统内存的40%左右,太大时会使系统因动用虚拟内存从而太吃力。
sql语句的优化级别:一般取2或5(最高为9)
Default query optinization class <DFT_QUENYOPT>=5
该值越大优化越好,但优化所化时间也越长。