随笔-25  评论-6  文章-0  trackbacks-0
  2006年7月20日

Question:
The restore command works fine, but while attempting the rolforward of the sql logs, it complains about database falling short on bufferpool,and then terminates the rollforward process. One close look at the db2diag.log file, I noticed that db2 tried to start the database with the hidden bufferpool. But, apparently, that hidden bufferpool was pretty small to rollforward the logs and bring it online.

I cannot reduce the bufferpool size as the database cannot be connected to.I cannot connect to the database as it is in rollforward pending state. I cannot rollforward the database, as it's not happy with the size of the *hidden* bufferpool and terminates.

Answer:

db2set DB2_OVERRIDE_BPF=50000

This will bring up all configured bufferpools using 50000 pages each. You
can choose a smaller/larger value that is suitable for your number of
bufferpools and available system memory. You can also configure each
bufferpool individually if you want

値: 正数のページ数
     OR
 <entry>[;<entry>...] (<entry>=<バッファー・プール ID>,<ページ数> )

There is sitiuation that above solution does not work.

				When you try to create a bufferpool or alter a bufferpool to a
very large size and there is not enough memory in the system
, DB2 may occupies all pagespace and overrall performance of
the system become slow and may get hang at last because no
pagespace is available. Then after you connect the database
next time, DB2 will do crash recovery and still try to
allocate memory for this big bufferpool and occupy all
pagespace again. when you specify DB2_OVERRIDE_BPF parameter
to override bufferpool size, it doesn't take effect in this
situation. This is becasue DB2_OVERRIDE_BPF only applies for
bufferpools that already exist at startup, and not to
bufferpools that are created during crash recovery or roll
forward. We will fix this problem and check DB2_OVERRIDE_BPF
registry when creating bufferpools during crash recovery or
roll forward. This problem only occurs in a 64 bit instance.

		

Local fix

				You can use db2iupdt -w 32 <INSTNAME> to update the instance to
a 32 bit instance, then you can connect to the database
succefully. After that, use db2iupdt -w 64 <INSTNAME> to update
the instance to 64 bit again. Please take a backup at this
point, so we don't have to roll forward through bufferpool
creation that fails if we need restore and roll forward
database.

		

Problem summary

				Users Affected:
All users using 64 bit instance
Problem Description:
When you try to create a bufferpool or alter a bufferpool to a
very large size and there is not enough memory in the system
, DB2 may occupies all pagespace and overrall performance
of the system become slow and may get hang at last
because no pagespace is available. Then after you connect the
database at next time, DB2 will do crash recovery and still try
to allocate
memory for this big bufferpool and occupy all pagespace again.
In this situation, when you specify DB2_OVERRIDE_BPF parameter
to override bufferpool size, it doesn't take effect in this
situation. This
is becasue DB2_OVERRIDE_BPF only applies for bufferpools that
already exist at startup, and not to bufferpools that are
created during crash recovery or roll forward. We will fix
this problem and check
DB2_OVERRIDE_BPF registry when creating bufferpools during crash
recovery or roll forward. This problem only occurs in 64 bit
instance.
Problem Summary:
This problem is caused by a misoperation, when you create or alt
er a bufferpool, the size is too large to allocated from OS and
cause overrall performance of the system is very slow and seems
hang. Another problem is that DB2_OVERRIDE_BPF registry only app
lies to bufferpools that already exists, and not bufferpools wil
l be created in crash recovery or roll forward. So DB2 will try
to create this big bufferpool again when doing crash recovery or
 roll forward. We will fix this problem and check DB2_OVERRIDE_B
PF registry in our crash recovery and roll forward code.

		

Problem conclusion

				
				
		

Temporary fix

				You can use db2iupdt -w 32 <INSTNAME> to update the instance to
a 32 bit instance, then you can connect to the database
succefully. After that, use db2iupdt -w 64 <INSTNAME> to update
the instance to 64 bit again. Please take a backup at this
point, so we don't have to roll forward through bufferpool
creation that fails if we need restore and roll
forward database.Please also notice that be careful when creati
ng bufferpool, don't specify a too large value.

		


posted @ 2007-03-15 15:21 MyJavaWorld 阅读(717) | 评论 (0)编辑 收藏

Change db2 password in db2 level

DB2 depends on operation system level authorization to control DB2 system access.

In some case, our db2 account only allows to connect to instance or database, but not log on the system. In other words, we are not able to use the account to get a shell on unix or logon locally on windows.

As usual, when we need to change db2 password, we take action on the system level because it's more frank. But in the case above that we can't get logon, we have to do it on db2 level. There are 2 ways.

  • Use the GUI tool DB2 Configuration Assistance
  • Use the command line tools DB2 CLP or CE

Using DB2 Configuration Assistance

Right click on a database name, then choose "Change password".

CA tool interface

Note: When more than one databases live in same system, we might share the same account in multi-database. Changing password for one of them will affect all databases in this system. In other words, we don't need to do the change on each database, we could choose any we have privileges on the system.

Limitation: We are not able to change our password in the case of that we are only allowed to attach to the node but not connect to any database, or we don't get the catalog information for any database in the node.

For this limitation, it works out with the 2nd way. 

Using DB2 CLP and CE

We could use CLP and CE to change password for databases and nodes that we connected or attached to.

  • Change by connecting to database
C:\> db2 connect to SAMPLE user TEST using OLDPWD new NEWPWD confirm NEWPWD
C:\> db2 connect to SAMPLE user TEST using OLDPWD change password
  • Change by attaching to node, this way works out for the limitation in Configuration Assistance
C:\> db2 attach to NODE user TEST using OLDPWD new NEWPWD confirm NEWPWD
C:\> db2 attach to NODE user TEST using OLDPWD change password


alter table xxx VOLATILE

valatile

  • a. 反复无常的,挥发性的

VOLATILE CARDINALITY or NOT VOLATILE CARDINALITY
Indicates to the optimizer whether or not the cardinality of table table-name can
vary significantly at run time. Volatility applies to the number of rows in the
table, not to the table itself. CARDINALITY is an optional keyword. The default
is NOT VOLATILE.

VOLATILE
Specifies that the cardinality of table table-name can vary significantly at
run time, from empty to large. To access the table, the optimizer will use
an index scan (rather than a table scan, regardless of the statistics) if that
index is index-only (all referenced columns are in the index), or that index
is able to apply a predicate in the index scan. The list prefetch access method
will not be used to access the table. If the table is a typed table, this option
is only supported on the root table of the typed table hierarchy (SQLSTATE 428DR).

NOT VOLATILE
Specifies that the cardinality of table-name is not volatile.
Access plans to this table will continue to be based on existing statistics and
on the current optimization level.

NOTE: The keyword could be specified within ALTER TABLE, but not CREATE TABLE.

 

Difference between Local and System Database Directory

DB2 automatically catalogs databases when they are created. It catalogs an entry
for the database in the local database directory and another entry in the system
database directory. If the database is created from a remote client (or a client which
is executing from a different instance on the same machine), an entry is also made
in the system database directory at the client instance.

Databases on the same node as the database manager instance are cataloged as
indirect entries. Databases on other nodes are cataloged as remote entries.

List DBs in Local Database Directory

$ db2 list db directory on /path_to_where_db_created 

List DBs in System Database Directory

$ db2 list db directory

 

Illustration of standard tables

Standard Tables Overview

Query the status for one specified tablespace?

As we know, we could issue following command to query status for all of tablespaces in current connected DB.

$ db2 list tablespaces show detail > /tmp/ts.list

Then find the status for the tablespaces we concerned.

Is there's a way to query the status for one specified tablespace?

My answer is No. 

  1. First, I don't find the related column defination in the table or view:
    • sysibm.systablespaces
    • syscat.tablespaces
  2. Second, I don't think DB2 stores the status flag within syscata tables. The reason is that once a tablespace comes into a special status, it will not be allowed changing any longer(this may also happen on a system catalog tablespace.) that will lead to a conflict on changing the tablespace status flag if stores it within system catalog tables.

Illustration of the DMS table-space address map

address map for DMS TS

DB2 directories and files

  • http://publib.boulder.ibm.com/infocenter/db2luw/v8//topic/com.ibm.db2.udb.doc/admin/c0005420.htm

Illustration of DB2 architechure and process

overview for tuning

Reference

  • http://publib.boulder.ibm.com/infocenter/db2luw/v8//topic/com.ibm.db2.udb.doc/admin/c0005418.htm 

Tablespaces are put into backup pending after a load

DB2 sets tablespace as Backup Pending state after loading data into a table in linear logging database(that is, logretain or userexit is on), whatever the load is successful or failed. the reason is that the load process will not write log file. from the begin time of loading to the end time of loading, there will be a blank segment in log file, and the rollforward recovery can Not jump over the blank segment to apply the later log file.

so database needs a backup after loading to make sure db2 have recovery capicibility.

it's able to use [COPY YES|NO]  or [NONRECOVERABLE] to prevent tablespace go into Backup Pending state. COPY YES will do the backup automatically after loading, and COPY NO and NONRECOVERABLE will give up this backup that means db2 will be not able to recover the database once an serious error occured.


继续阅读 "Tablespaces are put into backup pending after a load" 的剩余内容

Come pending when droping Procedures

Problem Description 

There's no any response for creating or droping any procedures in DB2. Seems it's pending there, without any error returned. This time UPDATE statement on tables could be issued successfully.

Check Process

Check OS disk available

$ df -kl 

Check database configure

db2 => get db cfg |more 

Check system catalog tablespace 

db2 => list tablespaces show detail |more
syscatspace 0x0000 

Cause 

It caused by issuing CREATE or DROP statement without COMMIT or ROLLBACK statement in CLP which is in non-Autocommit mode.

Solution 

After you issue a COMMIT or a ROLLBACK in the CLP or close it, the pending is gone.

We must be very careful when we use client in non-Autocommit mode just like CLPs in this case.

To check the Autocommit mode in CLP issues. Refer to:

set COMMIT mode in db2 clp

db2 => list command options

-c 自动落实 OFF

More 

From this point, we could get more. Most of strange things like this(pending there and no error return) are caused by locking.

In this case, it was only the opertation on procedures being pended, so track on this thread to suppose the syscat tables related with procedures are locked then find the what probably causes it.
 

db2 can not create index on local view

There's an object called index view since MS SQL Server 2000, it's an index which is created on an view which is based on a local table. it is attent to imporve the select performence on the view when this view is based on multi-table and has complex logic.

I try to find a simular thing in DB2, but there's no the simular solution in DB2 v8.2 for now. Instead, I found another thing instested.

DB2 allows creating index on the tables or views in remote data source, such as a database on another host or an XML data source. To be exactly, that's Not true Index, it's Index Specification. It requests that the tables in remote data source have created index in its own system. And it only repeat the index description in local system.

										Local DB2 Env                                            Remote DB2 Env
										

Index Specification    ->    Nickname   - - ->   True Index    ->    Table

See following example in DB2 info center.

  • CREATE INDEX statement
    http://publib.boulder.ibm.com/infocenter/db2luw/v8//topic/com.ibm.db2.udb.doc/admin/r0000919.htm?resultof=%22%63%72%65%61%74%65%22%20%22%63%72%65%61%74%22%20%22%69%6e%64%65%78%22%20%22%73%74%61%74%65%6d%65%6e%74%22%20

Example 3:  The nickname EMPLOYEE references a data source table called CURRENT_EMP. After this nickname was created, an index was defined on CURRENT_EMP. The columns chosen for the index key were WORKDEBT and JOB. Create an index specificationindex. Through this specification, the optimizer will know that the index exists and what its key is. With this information, the optimizer can improve its strategy to access the table. that describes this

   CREATE UNIQUE INDEX JOB_BY_DEPT
ON EMPLOYEE (WORKDEPT, JOB)
SPECIFICATION ONLY

Note: the Nickname is only allowed to be created on tables in local database and on much kind of objects at remote data source. It's not allowed to be created on views in local database.

set COMMIT mode in db2 clp

As default, DB2 CLP will do commit after you issue each DB2 statements or SQL automatically.

If you want to change it instead of issuing COMMIT or ROLLBACK manually, do following.

SQLLIB\BIN> db2
db2 => list command options
    -c   ON
db2 => update command options using c off
db2 => list command options
    -c   OFF

This change will only exists during this session. The setting will lose when you close this CLP and open CLP next time.

following cmd will get the same result with above.

SQLLIB\BIN> db2 list command options
    -c    ON
SQLLIB\BIN> db2 +c
db2 =>
db2 => list command options
    -c    OFF
db2 => quit
SQLLIB\BIN> db2 list command options
    -c    ON

There's also the way to keep the settings forever, do following.

SQLLIB\BIN\> db2 list command options
    -c   ON
SQLLIB\BIN\> db2set db2options=+c
SQLLIB\BIN\> db2 list command options
    -c   OFF

This change will take effection immediately even for others having been opened CLP windows. And will keep along.

Use following cmd set it back to ON. 

SQLLIB\BIN> db2set db2opptions=-c

Reference

表与索引的重命名 RENAME

在DB2 中重命名表或者索引

db2=> RENAME TABLE EMP TO EMPLOYEE
db2=> RENAME TABLE ABC.EMP TO EMPLOYEE
db2=> RENAME INDEX NEW-IND TO IND
db2=> RENAME INDEX ABC.NEW-IND TO IND
posted @ 2007-03-15 15:00 MyJavaWorld 阅读(502) | 评论 (0)编辑 收藏
三个UNIX文件时间ctime、mtime、atime
       我曾经根据文件的状态在指定时间内是否改变写过一个WatchDog来对服务进行监控,其间曾被这三个时间搞混淆,所以觉得很有必要和大家分享我对这三个术语的理解。
      ctime(change time)改变时间:是指文件状态最后一次被改变的时间;
      mtime(modification time)修改时间:是指文件内容最后一次被改变的时间;
      atime(access time)访问时间:是指文件最后一次被读取的时间。
      前两者的区别就在于文件状态的改变既包括文件索引节点的改变,也包括文件内容的改变。也就是说如果你改变了文件内容,则同时更新了ctime和mtime,但是如果你只改变了文件索引节点则只是改变了ctime。atime只有在文件被读取的时侯才会改变。它的改变与文件状态以及文件内容的改变没有直接的联系。
     例如:echo “Hello World” >> myfile 则同时改变了ctime和mtime,atime不变;
     chmod u+x myfile 则只改变了ctime,mtime和atime不变。
     cat myfile,则只改变了atime,ctime和mtime不变
     ps:以上操作均在redhat linux下验证通过
posted @ 2007-03-13 17:51 MyJavaWorld 阅读(1158) | 评论 (0)编辑 收藏
 
 
查看文章
 
DB2/SQL命令大全
2006-12-25 13:21

连接数据库:

  connect to [数据库名] user [操作用户名] using [密码] 

创建缓冲池(8K):

  create bufferpool ibmdefault8k IMMEDIATE  SIZE 5000 PAGESIZE 8 K ;
创建缓冲池(16K)(OA_DIVERTASKRECORD):
  create bufferpool ibmdefault16k IMMEDIATE  SIZE 5000 PAGESIZE 16 K ;
创建缓冲池(32K)(OA_TASK):
  create bufferpool ibmdefault32k IMMEDIATE  SIZE 5000 PAGESIZE 32 K ;

创建表空间:

  CREATE TABLESPACE exoatbs IN DATABASE PARTITION GROUP IBMDEFAULTGROUP PAGESIZE 8K MANAGED BY SYSTEM USING ('/home/exoa2/exoacontainer') EXTENTSIZE 32 PREFETCHSIZE 16  BUFFERPOOL IBMDEFAULT8K  OVERHEAD 24.10 TRANSFERRATE 0.90  DROPPED TABLE RECOVERY OFF;

  CREATE TABLESPACE exoatbs16k  IN DATABASE PARTITION GROUP IBMDEFAULTGROUP PAGESIZE 16K MANAGED BY SYSTEM USING ('/home/exoa2/exoacontainer16k'   ) EXTENTSIZE 32  PREFETCHSIZE 16  BUFFERPOOL IBMDEFAULT16K  OVERHEAD 24.1 TRANSFERRATE 0.90  DROPPED TABLE RECOVERY OFF;

  CREATE TABLESPACE exoatbs32k  IN DATABASE PARTITION GROUP IBMDEFAULTGROUP PAGESIZE 32K MANAGED BY SYSTEM USING ('/home/exoa2/exoacontainer32k'   ) EXTENTSIZE 32  PREFETCHSIZE 16  BUFFERPOOL IBMDEFAULT32K  OVERHEAD 24.1 TRANSFERRATE 0.90  DROPPED TABLE RECOVERY OFF;

GRANT USE OF TABLESPACE exoatbs TO PUBLIC;
GRANT USE OF TABLESPACE exoatbs16k TO PUBLIC;
GRANT USE OF TABLESPACE exoatbs32k TO PUBLIC;

创建系统表空间:

  CREATE TEMPORARY TABLESPACE exoasystmp IN DATABASE PARTITION GROUP IBMTEMPGROUP PAGESIZE 8K  MANAGED BY SYSTEM USING ('/home/exoa2/exoasystmp'   ) EXTENTSIZE 32 PREFETCHSIZE 16 BUFFERPOOL IBMDEFAULT8K  OVERHEAD 24.10 TRANSFERRATE 0.90  DROPPED TABLE RECOVERY OFF;

  CREATE TEMPORARY TABLESPACE exoasystmp16k IN DATABASE PARTITION GROUP IBMTEMPGROUP PAGESIZE 16K MANAGED BY SYSTEM USING ('/home/exoa2/exoasystmp16k'  ) EXTENTSIZE 32 PREFETCHSIZE 16 BUFFERPOOL IBMDEFAULT16K OVERHEAD 24.10 TRANSFERRATE 0.90  DROPPED TABLE RECOVERY OFF;

  CREATE TEMPORARY TABLESPACE exoasystmp32k IN DATABASE PARTITION GROUP IBMTEMPGROUP PAGESIZE 32K MANAGED BY SYSTEM USING ('/home/exoa2/exoasystmp32k') EXTENTSIZE 32 PREFETCHSIZE 16 BUFFERPOOL IBMDEFAULT32K OVERHEAD 24.10 TRANSFERRATE 0.90  DROPPED TABLE RECOVERY OFF;

1. 启动实例(db2inst1):

db2start

2. 停止实例(db2inst1):

db2stop

3. 列出所有实例(db2inst1)

db2ilist

5.列出当前实例:

db2 get instance

4. 察看示例配置文件:

db2 get dbm cfg|more

5. 更新数据库管理器参数信息:

db2 update dbm cfg using para_name para_value

6. 创建数据库:

db2 create db test

7. 察看数据库配置参数信息

db2 get db cfg for test|more

8. 更新数据库参数配置信息

db2 update db cfg for test using para_name para_value

10.删除数据库:

db2 drop db test

11.连接数据库

db2 connect to test

12.列出所有表空间的详细信息。

db2 list tablespaces show detail

13.查询数据:

db2 select * from tb1

14.删除数据:

db2 delete from tb1 where id=1

15.创建索引:

db2 create index idx1 on tb1(id);

16.创建视图:

db2 create view view1 as select id from tb1

17.查询视图:

db2 select * from view1

18.节点编目

db2 catalog tcp node node_name remote server_ip server server_port

19.察看端口号

db2 get dbm cfg|grep SVCENAME

20.测试节点的附接

db2 attach to node_name

21.察看本地节点

db2 list node direcotry

22.节点反编目

db2 uncatalog node node_name

23.数据库编目

db2 catalog db db_name as db_alias at node node_name

24.察看数据库的编目

db2 list db directory

25.连接数据库

db2 connect to db_alias user user_name using user_password

26.数据库反编目

db2 uncatalog db db_alias

27.导出数据

db2 export to myfile of ixf messages msg select * from tb1

28.导入数据

db2 import from myfile of ixf messages msg replace into tb1

29.导出数据库的所有表数据

db2move test export

30.生成数据库的定义

db2look -d db_alias -a -e -m -l -x -f -o db2look.sql

31.创建数据库

db2 create db test1

32.生成定义

db2 -tvf db2look.sql

33.导入数据库所有的数据

db2move db_alias import

34.重组检查

db2 reorgchk

35.重组表tb1

db2 reorg table tb1

36.更新统计信息

db2 runstats on table tb1

37.备份数据库test

db2 backup db test

38.恢复数据库test

db2 restore db test

399\.列出容器的信息

db2 list tablespace containers for tbs_id show detail

40.创建表:

db2 ceate table tb1(id integer not null,name char(10))

41.列出所有表

db2 list tables

42.插入数据:

db2 insert into tb1 values(1,’sam’);

db2 insert into tb2 values(2,’smitty’);

. 建立数据库DB2_GCB 

CREATE DATABASE DB2_GCB ON G: ALIAS DB2_GCB 

USING CODESET GBK TERRITORY CN COLLATE USING SYSTEM DFT_EXTENT_SZ 32 

2. 连接数据库 

connect to sample1 user db2admin using 8301206 

3. 建立别名 

create alias db2admin.tables for sysstat.tables; 

CREATE ALIAS DB2ADMIN.VIEWS FOR SYSCAT.VIEWS 

create alias db2admin.columns for syscat.columns; 

create alias guest.columns for syscat.columns; 

4. 建立表 

create table zjt_tables as 

(select * from tables) definition only; 

create table zjt_views as 

(select * from views) definition only; 

5. 插入记录 

insert into zjt_tables select * from tables; 

insert into zjt_views select * from views; 

6. 建立视图 

create view V_zjt_tables as select tabschema,tabname from zjt_tables; 

7. 建立触发器 

CREATE TRIGGER zjt_tables_del 

AFTER DELETE ON zjt_tables 

REFERENCING OLD AS O 

FOR EACH ROW MODE DB2SQL 

Insert into zjt_tables1 values(substr(o.tabschema,1,8),substr(o.tabname,1,10)) 

8. 建立唯一性索引 

CREATE UNIQUE INDEX I_ztables_tabname 

[size=3]ON zjt_tables(tabname); 

9. 查看表 

select tabname from tables 

where tabname='ZJT_TABLES'; 

10. 查看列 

select SUBSTR(COLNAME,1,20) as 列名,TYPENAME as 类型,LENGTH as 长度 

from columns 

where tabname='ZJT_TABLES'; 

11. 查看表结构 

db2 describe table user1.department 

db2 describe select * from user.tables 

12. 查看表的索引 

db2 describe indexes for table user1.department 

13. 查看视图 

select viewname from views 

where viewname='V_ZJT_TABLES'; 

14. 查看索引 

select indname from indexes 

where indname='I_ZTABLES_TABNAME'; 

15. 查看存贮过程 

SELECT SUBSTR(PROCSCHEMA,1,15),SUBSTR(PROCNAME,1,15) 

FROM SYSCAT.PROCEDURES; 

16. 类型转换(cast) 

ip datatype:varchar 

select cast(ip as integer)+50 from log_comm_failed 

17. 重新连接 

connect reset 

18. 中断数据库连接 

disconnect db2_gcb 

19. view application 

LIST APPLICATION; 

20. kill application 

FORCE APPLICATION(0); 

db2 force applications all (强迫所有应用程序从数据库断开) 

21. lock table

lock table test in exclusive mode 

22. 共享 

lock table test in share mode 

23. 显示当前用户所有表 

list tables 

24. 列出所有的系统表 

list tables for system 

25. 显示当前活动数据库 

list active databases 

26. 查看命令选项 

list command options 

27. 系统数据库目录 

LIST DATABASE DIRECTORY 

28. 表空间 

list tablespaces 

29. 表空间容器 

LIST TABLESPACE CONTAINERS FOR 

Example: LIST TABLESPACE CONTAINERS FOR 1 

30. 显示用户数据库的存取权限 

GET AUTHORIZATIONS 

31. 启动实例 

DB2START 

32. 停止实例 

db2stop 

33. 表或视图特权 

grant select,delete,insert,update on tables to user 

grant all on tables to user WITH GRANT OPTION 

34. 程序包特权 

GRANT EXECUTE 

ON PACKAGE PACKAGE-name 

TO PUBLIC 

35. 模式特权 

GRANT CREATEIN ON SCHEMA SCHEMA-name TO USER 

36. 数据库特权 

grant connect,createtab,dbadm on database to user 

37. 索引特权 

grant control on index index-name to user 

38. 信息帮助 (? XXXnnnnn ) 

例:? SQL30081 

39. SQL 帮助(说明 SQL 语句的语法) 

help statement 

例如,help SELECT 

40. SQLSTATE 帮助(说明 SQL 的状态和类别代码) 

? sqlstate 或 ? class-code 

41. 更改与"管理服务器"相关的口令 

db2admin setid username password 

42. 创建 SAMPLE 数据库 

db2sampl 

db2sampl F:(指定安装盘) 

43. 使用操作系统命令 

! dir 

44. 转换数据类型 (cast) 

SELECT EMPNO, CAST(RESUME AS VARCHAR(370)) 

FROM EMP_RESUME 

WHERE RESUME_FORMAT = 'ascii' 

45. UDF

要运行 DB2 Java 存储过程或 UDF,还需要更新服务器上的 DB2 数据库管理程序配置,以包括在该机器上安装 JDK 的路径 

db2 update dbm cfg using JDK11_PATH d:sqllibjavajdk 

TERMINATE 

update dbm cfg using SPM_NAME sample 

46. 检查 DB2 数据库管理程序配置 

db2 get dbm cfg 

47. 检索具有特权的所有授权名 

SELECT DISTINCT GRANTEE, GRANTEETYPE, 'DATABASE' FROM SYSCAT.DBAUTH 

UNION 

SELECT DISTINCT GRANTEE, GRANTEETYPE, 'TABLE ' FROM SYSCAT.TABAUTH 

UNION 

SELECT DISTINCT GRANTEE, GRANTEETYPE, 'PACKAGE ' FROM SYSCAT.PACKAGEAUTH 

UNION 

SELECT DISTINCT GRANTEE, GRANTEETYPE, 'INDEX ' FROM SYSCAT.INDEXAUTH 

UNION 

SELECT DISTINCT GRANTEE, GRANTEETYPE, 'COLUMN ' FROM SYSCAT.COLAUTH 

UNION 

SELECT DISTINCT GRANTEE, GRANTEETYPE, 'SCHEMA ' FROM SYSCAT.SCHEMAAUTH 

UNION 

SELECT DISTINCT GRANTEE, GRANTEETYPE, 'SERVER ' FROM SYSCAT.PASSTHRUAUTH 

ORDER BY GRANTEE, GRANTEETYPE, 3 

create table yhdab 

(id varchar(10), 

password varchar(10), 

ywlx varchar(10), 

kh varchar(10)); 

create table ywlbb 

(ywlbbh varchar(8), 

ywmc varchar(60)) 

48. 修改表结构 

alter table yhdab ALTER kh SET DATA TYPE varchar(13); 

alter table yhdab ALTER ID SET DATA TYPE varchar(13); 

alter table lst_bsi alter bsi_money set data type int; 

insert into yhdab values 

('20000300001','123456','user01','20000300001'), 

('20000300002','123456','user02','20000300002'); 

49. 业务类型说明 

insert into ywlbb values 

('user01','业务申请'), 

('user02','业务撤消'), 

('user03','费用查询'), 

('user04','费用自缴'), 

('user05','费用预存'), 

('user06','密码修改'), 

('user07','发票打印'), 

('gl01','改用户基本信息'), 

('gl02','更改支付信息'), 

('gl03','日统计功能'), 

('gl04','冲帐功能'), 

('gl05','对帐功能'), 

('gl06','计费功能'), 

('gl07','综合统计') 

备份数据库:
CONNECT TO EXOA;
QUIESCE DATABASE IMMEDIATE FORCE CONNECTIONS;
CONNECT RESET;
BACKUP DATABASE EXOA TO "/home/exoa2/db2bak/" WITH 2 BUFFERS BUFFER 1024 PARALLELISM 1 WITHOUT PROMPTING;
CONNECT TO EXOA;
UNQUIESCE DATABASE;
CONNECT RESET;

以下是小弟在使用db2move中的一些经验,希望对大家有所帮助。 

 db2   connect   to  YOURDB   
连接数据库 

 db2look -d  YOURDB  -a -e -x -o creatab.sql 
导出建库表的SQL 

 db2move   YOURDB  export 
用db2move将数据备份出来 

 vi   creatab.sql 
如要导入的数据库名与原数据库不同,要修改creatab.sql中CONNECT 项 
如相同则不用更改 

 db2move  NEWDB  load 
将数据导入新库中 

在导入中可能因为种种原因发生中断,会使数据库暂挂 
db2    list tablespaces   show   detail 
如: 
      详细说明: 
     装入暂挂 
 总页数                          = 1652 
 可用页数                        = 1652 
 已用页数                         = 1652 
 空闲页数                         = 不适用 
 高水位标记(页)                 = 不适用 
 页大小(字节)                   = 4096 
 盘区大小(页)                   = 32 
 预读取大小(页)                 = 32 
 容器数                           = 1 
 状态更改表空间标识                    = 2 
 状态更改对象标识                      = 59 

 db2 select tabname,tableid from syscat.tables where tableid=59 
查看是哪张表挂起 

表名知道后到db2move.lst(在db2move  YOURDB  export的目录中)中找到相应的.ixf文件 
 db2 load from tab11.ixf of ixf terminate into db2admin.xxxxxxxxx 
tab11.ixf对应的是xxxxxxxxx表 

数据库会恢复正常,可再用db2 list tablespaces show detail查看

30.不能通过GRANT授权的权限有哪种?

SYSAM

SYSCTRL

SYSMAINT

要更该述权限必须修改数据库管理器配置参数

31.表的类型有哪些?

永久表(基表)

临时表(说明表)

临时表(派生表)

32.如何知道一个用户有多少表?

SELECT*FROMSYSIBM.SYSTABLESWHERECREATOR='USER'

33.如何知道用户下的函数?

select*fromIWH.USERFUNCTION

select*fromsysibm.SYSFUNCTIONS

34.如何知道用户下的VIEW数?

select*fromsysibm.sysviewsWHERECREATOR='USER'

35.如何知道当前DB2的版本?

select*fromsysibm.sysvERSIONS

36.如何知道用户下的TRIGGER数?

select*fromsysibm.SYSTRIGGERSWHERESCHEMA='USER'

37.如何知道TABLESPACE的状况?

select*fromsysibm.SYSTABLESPACES

38.如何知道SEQUENCE的状况?

select*fromsysibm.SYSSEQUENCES

39.如何知道SCHEMA的状况?

select*fromsysibm.SYSSCHEMATA

40.如何知道INDEX的状况?

select*fromsysibm.SYSINDEXES

41.如何知道表的字段的状况?

select*fromsysibm.SYSCOLUMNSWHERETBNAME='AAAA'

42.如何知道DB2的数据类型?

select*fromsysibm.SYSDATATYPES

43.如何知道BUFFERPOOLS状况?

select*fromsysibm.SYSBUFFERPOOLS

44.DB2表的字段的修改限制?

只能修改VARCHAR2类型的并且只能增加不能减少.

45.如何查看表的结构?

DESCRIBLETABLETABLE_NAME

OR

DESCRIBLESELECT*FROMSCHEMA.TABLE_NAME

 
 

     
 
posted @ 2006-12-28 16:57 MyJavaWorld 阅读(2735) | 评论 (0)编辑 收藏

DB2 UDB中用户出口程序是如何工作的?

 

采用用户出口程序与DB2 UDB共同工作背后的基本思想是提供一种归档和检索数据库日志文件的方法以实现日志冗余处理并从易失性介质上转储出来。重要的,值得注意的是,根据你的特殊需求,在用户出口程序当中,除了能实现归档和检索日志之外,你还可以实现其他的操作。

 

如果一个数据库需要采用归档日志文件来进行恢复,在DB2 UDB中实行用户出口程序策略将不能恢复100%的事务。用户出口程序只是一种通过拷贝已经存在的日志文件到一个安全的地方来为其提供更多保护的方法。它是数据完整性策略中的一部分,而且是重要的一部分。

 

编译了用户出口程序之后,可执行程序db2uext2被放置在数据库管理器可以找到的目录当中。在UNIX©中,这个目录是/sqllib/adm;在Windows©中,是Program FilesIBMSQLLIBBIN。

 

除非数据库管理器知道用户出口程序是可用的,不然它不会调用db2uext2。让数据库管理器知道db2uext2可以被调用的唯一方法是将数据库配置参数userexit设置为on。一旦这个参数被设定好而且DB2实例被重复利用了,数据库管理器将每五分钟调用一次用户出口程序来检查那些可以被归档到程序相关的归档目录的日志文件。

 

如果数据库的恢复是必要的,在前滚操作期间,数据库管理器将调用db2uext2把归档日志文件拷贝回活动的日志目录当中。然后,日志文件被再次运用到重建的数据库中。

 

让我们看看被数据库管理器生成的到用户出口程序的调用的格式。注意,这一信息也可以在用户出口示例程序的注释部分找到。

db2uext2 -OS -RL

-RQ -DB -NN

-LP -LN [-AP]

 

其中:

os=操作系统

release=DB2发行版本

request= 'ARCHIVE' 或 'RETRIEVE'

dbname=数据库名

nodenumber=节点号

logpath=日志文件目录

logname=日志文件名

logsize=日志文件大小(可选)

startingpage=以4k页为单位的起始偏移量(可选)

adsmpasswd=ADSM密码(可选)

 

注意:只有当logpath为裸设备时才使用logsize和startingpage。

 

归档或者从磁盘检索日志文件遵从以下命名规则:

归档:归档路径+数据库名+节点号+日志文件名

检索:检索路径+数据库名+节点号+日志文件名

 

比如:如果归档的路径为”c:mylogs”,

检索路径是“c:mylogs”,

数据库名是“SAMPLE”,

节点号是 NODE0000,

文件名是 S0000001.LOG,

日志文件将是:

归档到 - c:mylogsSAMPLENODE0000S0000001.LOG

检索自 - c:mylogsSAMPLENODE0000S0000001.LOG

以下描述了用户出口程序中的逻辑是如何运转的:

1)  安装信号处理程序。

2)  验证传递的参数个数。

3)  验证操作请求。

4)  开始审计跟踪(如果有此请求)。

5)  根据操作需求的不同获取以下路径中的一个:

a)  如果操作需求为归档一个文件,将日志文件从日志路径拷贝到归档路径中。

i) 如果没有找到日志文件,执行第6点。

 

b)  如果操作需求是检索一个文件,将日志文件从检索路径拷贝到日志路径中。

i) 如果没有找到日志文件,执行第6点。

6) 将错误记入日志(如果要求或者有需要的话)。

7)  结束审计跟踪(如果有请求)。

8)  以适当的返回码退出。

 

手工调用用户出口程序来归档日志文件是可以的,但最好还是使用ARCHIVE LOG命令以便在定义以上参数时不会因为你的原因导致错误。在这篇文章的末尾,可以找到关于ARCHIVE LOG命令的链接。

 

日志文件术语

 

DB2 中用户出口程序的基本功能是将日志文件拷贝到活动日志目录或反之。这里,值得指出一些术语来阐明活动的日志目录被置于何处以及数据库日志文件的状态如何。

 

活动日志目录:

 

该目录被置于你的数据库目录中。在Windows中,如果在C:中创建了一个叫做SAMPLE的单一数据库且实例名为db2inst1,则将会出现以下的目录结构:

 

C:DB2INST1NODE0000SQL000001SQLOGDIR

 

SQL00001是SAMPLE数据库的数据库目录,SQLOGDIR 是活动日志目录。

 

以下的图1显示了Windows操作系统上的活动日志目录:

PATH o:extrusionok="f" gradientshapeok="t" o:connecttype="rect" />SHAPE id=_x0000_i1025 style="WIDTH: 299.25pt; HEIGHT: 180.75pt" type="#_x0000_t75" />/P>

 

图 1活动日志目录

日志文件状态

 

在活动日志目录中,日志文件可以是活动日志,也可以是联机归档日志。活动日志是那些被 DB2 用于当前事务处理和崩溃恢复的日志。联机归档日志是那些 DB2 UDB 进行常规处理时不再需要,而进行数据库恢复时可能还会需要的日志。当实现用户出口程序时,这些联机归档日志将最终以归档日志目录中的副本形式出现。

 

既然 DB2 UDB 中用户出口程序的目的是将数据库日志拷贝到归档目录中,你将最终在活动日志目录(缺省为 SQLOGDIR)中得到重复的日志文件。你可能考虑删除这些重复的联机归档日志以释放文件系统空间。在从数据库目录中除去这些日志之前,要十分小心地确认它们是否已经将成功地被复制到归档目录中。还必须确保数据库管理器进行崩溃恢复时不再需要它们。要确定你的活动日志目录中哪些日志文件不为正常处理所需要,可用通过以下命令检查数据库配置:

        

     db2 "get db cfg for sample"

 

这条命令的数据库配置输出结果将包含第一个活动日志文件,如:

First active log file = S000009.LOG

 

在如上所示的输出当中,日志文件S000009.LOG是数据库当前的活动日志。任何编号比该日志文件小的日志文件都被看作联机归档日志。

 

这里有一个例子:

 

在这个场景中,活动日志目录中有日志文件 S000000.LOG - S000009.LOG,归档日志目录中有 S000000.LOG - S000008.LOG。因为 S000009.LOG 是第一个活动日志文件,所以,可以从活动日志目录中移走 S000001.LOG - S000008.LOG 以释放磁盘空间。S000009.LOG 文件必须保留在活动日志目录中,因为它仍然被当前事务使用。

 

同样可以通过检查数据库历史文件来查看活动日志目录中哪些日志文件不再有用。以下命令将列出数据库备份信息:

 

     db2 "list history backup all for database sample"

 

以下是该命令的输出结果的一个例子:

 

List History File for sample

Number of matching file entries = 4

Op Obj Timestamp+Sequence Type Dev Earliest Log Current  Log

-- --- ------------------ ---- --- ------------------------

B D 20030416162026001 F D S0000010.LOGS0000014.LOG

------------------------------------------------------------

Contains 2 tablespace(s):

00001 SYSCATSPACE

00002 USERSPACE1

------------------------------------------------------------

 

在上面的输出中,最早的日志将表示,需要 S0000010.LOG 及其之后的任何日志。 S00000010.LOG 之前的任何日志可以被安全的删除。再次提醒,在从活动日志目录中删除日志文件之前,验证在活动日志目录中存在这些日志文件的拷贝是十分重要的。

 

虽然可以手动的从活动日志目录中删除日志文件,删除联机归档日志文件的安全方法是通过prune logfile命令。该命令可以用来删除活动归档目录中的日志文件。在下面的示例中,以下命令将删除日志文件 S000000.LOG - S000008.LOG:

     db2 "prune logfile prior to S000009.LOG"

 

注意:根据您的恢复策略,可能会出现之前的前滚操作在数据库上执行的场景。归档目录中的老日志文件可能被同名的新日志文件所覆盖,从而阻止你使用旧日志文件对数据库进行时间点恢复。对用户出口程序的设计程序员来说,考虑类似这样的情况是很重要的。

 

设置用户出口

 

在本文中,我们将采用DB2提供的db2uext2.cdisk样例c程序,它位于你的c目录当中。在UNIX中,c目录位于/sqllib/samples。Windows中,这目录位于Program Files/IBM//samples。

 

在Windows中设置用户出口

 

修改和编译用户出口程序

1.  创建名为C:mylogs的目录

2.  将C:Program filesIBMSQLLIBsamplescdb2uext2.cdisk拷贝到一个工作目录当中

3.  对于本示例,用户出口程序的以下部分应该得以验证以反映路径 c:\mylogs\

 

#define ARCHIVE_PATH "c:\mylogs\"

#define RETRIEVE_PATH "c:\mylogs\"

#define AUDIT_ACTIVE 1 /* enable audit trail logging */

#define ERROR_ACTIVE 1 /* enable error trail logging */

#define AUDIT_ERROR_PATH "c:\mylogs\"

                 /* path must end with a slash */

#define AUDIT_ERROR_ATTR "a" /* append to text file */

#define BUFFER_SIZE 32

    /* # of 4K pages for output buffer */

 

4.  确定在你的系统中安装了被支持的C编译器(比如,Microsoft Visual Studio)而且环境中有该编译器的路径。

5.  通过命令行,将db2uext2.cdisk更名为db2uext2.c并构建:

cl db2uext2.c

一旦程序被编译,将创建db2uext2.exe和db2uext2.obj文件。

6.  将可执行文件db2uext2.exe放到/SQLLIB/BIN目录当中从而使数据库管理器能够定位并执行它用以归档和检索日志。

 

为用户出口创建并准备数据库

7.  在 DB2 命令窗口中用 db2sampl 命令创建 SAMPLE 数据库。这将使你对下面的示例使用样本表。

db2sampl

8.  更新数据库配置文件以便为数据库打开用户出口。请注意:只能为一个数据库分配用户出口程序,因为 bin 目录被所有 DB2 实例共享。

db2 "update db cfg for sample using userexit on"

db2stop force

<span lang="EN-US" style="FONT-SIZE: 10pt; COLOR: black; FONT-FAMILY: 宋体; mso-hansi-font-family: 'Times New Roman'; mso-bidi-font-family: 宋体; mso-

/P>
posted @ 2006-12-08 18:12 MyJavaWorld 阅读(406) | 评论 (0)编辑 收藏
其实主要的就是要创建一个密钥仓库以管理您的公钥 / 私钥对来自您所信任实体的证书。
 
第一步:生成密钥对
您首先要做的是创建一个密钥仓库和生成密钥对。您可以使用以下命令:  
keytool -genkey -keyalg RSA -keysize 512 -dname "cn=hyq,o=eagle,c=cn" -alias weblogic -keypass 123456 -keystore C:/mykeystore/weblogic.jks -storepass 123456 -validity 365

(请注意:键入该命令时必须使其成为一行。此处用多行来显示,主要是为了可读性。)如下图:
Snap2.gif

该命令将在  C  盘的 “mykeystore” 目录中创建名为 “weblogic.jks” 的密钥仓库,并赋予它口令 123456 。它将为实体生成公钥 / 私钥对,该实体的 特征名 为:常用名 “hyq” 、组织 “eagle” 和两个字母的国家代码 “cn” 。“ -keyalg ”指定它使用的是那种密钥生成算法来创建密钥,缺省的是 “DSA” 密钥生成算法(会使用缺省的  DSA   SHA1” 签名算法),两个密钥(公钥与私钥)的长度是 512 位,由 -keysize 来指定,默认的是 1024  位。   该证书包括公钥和特征名信息。该证书的有效期为 365 天,由 -validity 来指定,且与别名 “business” 所代表的密钥仓库项关联。私钥被赋予口令 123456

 

命令行里 DName 信息注解

 

DN 信息域

含义

CN

域名或 IP

OU

部门,没有部门的可不要此项

O

单位名称

L

单位地址

S

省份的拼音(第一个字母大写)

C

国家的简写 ( CN 代表中国)


如果采用选项的缺省值,可以大大缩短该命令。实际上,这些选项并不是必需的;对于有缺省值的选项,未指定时将使用缺省值,对于任何被要求的值,您将会得到要求输入它的提示。例如:输入命令 keytool -genkey -keystore "C:/tone.jks" -storepass 123456 -keyalg RSA ,就会有如下提示:
Snap3.gif


注意:这里的
密钥仓库路径一定要存在,如果不存在的话,它就会抛如下的异常

Snap4.gif
第二步
: 产生证书请求certreq.pem 文件

使用如下命令:

keytool -certreq -alias weblogic -sigalg "MD5withRSA" -file C:/mykeystore/certreq.pem -keypass 123456 -keystore C:/mykeystore/weblogic.jks -storepass 123456

Snap5.gif
这样在
C:/mykeystore/ 目录下 就会产生一个 certreq.pem 文件,内容如下:

-----BEGIN NEW CERTIFICATE REQUEST-----

MIHlMIGQAgEAMCsxCzAJBgNVBAYTAmNuMQ4wDAYDVQQKEwVlYWdsZTEMMAoGA1UEAxMDaHlxMFww

DQYJKoZIhvcNAQEBBQADSwAwSAJBAMhaIG2Ki7+RwZUP4gPBdTbnY38bisW16u1XUyysPxdNwSie

aSd6E3Hm277E7NjHoz56ZoaYdPPDmdiTkMrS9rcCAwEAAaAAMA0GCSqGSIb3DQEBBAUAA0EAYRNl

l5dyGgV9hhu++ypcJNQTrDIwjx1QT4fgVubrtIaHU0fzHamD5QG6PYddw9TL51XQHvu6tOS0NUc/

ItNKJw==

-----END NEW CERTIFICATE REQUEST-----

第三步:这就相对来说简单多了,就是CA提交证书请求。
    你可以随便从网上找一家免费的CA认证适用机构(很多的),然后按照上面的提示进行操作就可以了,这一步就要用到前面生成的certreq.pem 文件了。(注意:一定要下载根证书)
    将生成的证书和下载的根证书放至你比较容易找到的位置,我一般将它们和生成的jks文件放到一起。

第四步:导入证书
    通过命令:keytool -import -alias RootCA -trustcacerts -file C:/mykeystore/RootCADemo.cer -keystore C:/mykeystore/weblogic.jks -storepass 123456将根证书导入第一步生成的weblogic.jks中,接着将所有其它的证书按照此命令全部导入。(注意证书的别名不能重复,同时一定注意要用上 -trustcacerts,否则,你在以后使用时,它将会认为你导入的这些证书是不可信任的 ,就会导致你在配置SSL时不能正常的工作。)
    这就全部完成了密钥仓库的创建。然后就可以在支持这些证书格式的服务器上使用了。下一篇将会写一下在weblogic上如何配置双向SSL

posted @ 2006-10-31 17:18 MyJavaWorld 阅读(439) | 评论 (0)编辑 收藏
现在的DB2 UDB系统中, 主要通过锁和隔离级别这两个主要的工具来控制并发连接,维护数据库中的数据在高并发的环境下的安全。

我们在这里将简要的阐述一下锁和隔离级别。

锁:

DB2 UDB中, 锁的主要作用对象是表和行, 其他如表空间和索引也是锁的对象, 但是因为其多为系统控制, 管理员和用户使用较少,在这里就不涉及了。

对于行级锁和表级锁, 它们的区别不言而喻, 主要是锁的对象不同。 当然锁对象的不同连带也会影响DB2的并发能力。

DB2中的表级锁主要有以下几种:

1. IS锁: 此锁作用于整个表,表示拥有此锁的应用连接要读取表中的某些数据, 但是在此应用连接读取具体的数据时, 还必须获得该行的行级锁;

2. IX锁: 此锁作用于整个表,表示拥有此锁的应用连接需要独占使用表中的某些数据, 但是在此应用连接独占使用具体的数据时, 还必须获得该行上相应的行级锁;

3. SIX锁: 此锁是锁转换的产物,表示应用连接拥有S和IX锁的特性;

4. S锁: 此锁作用于整个表, 拥有此锁的应用连接可以读取表中的任何纪录;

5. U锁: 此锁作用于整个表, 拥有此锁的应用连接可以读取表中的任何纪录,也可以更新表中的纪录, 但是更新时需要再获得X锁; 此锁主要在“select … with update”语句建立的可更新游标中起作用, 其他的应用可以读取表中的纪录, 但是不能更新它;

6. X锁: 此锁作用于整个表, 拥有此锁的应用连接独占的使用表中的任何纪录;可以进行更新或其他操作;

7. Z锁: 此锁作用于整个表, 也称超级独占锁,主要是在象修改表的定义、 删除表这一类的语句中会使用。 拥有此锁的应用连接对该表有完全的控制权。 其他的任何应用不能读取或更新表中的任何纪录。

在这里我们主要要看一下 IS/IX/SIX这三个锁。 在这三个锁中IS/IX本身并不具备使得应用连接可以读取或更新纪录的能力,应用连接要读取和更新纪录时, 需要再得到相应的行级锁; 反之亦然, 任何应用要获得行级锁操作数据记录之前, 也必须获得某个相应的表级锁。 SIX锁也是类似的情况。这就是为什麽在很多情况下我们使用的是行级锁, 但是用快照(SNAPSHOT)等工具却能够看到有表级锁存在的原因。

那麽DB2中又有哪些行级锁呢? 让我们来看下面的这张图:

那麽DB2中又有哪些行级锁呢?

此图中列出了DB2中包含的行级锁。 表中的第三列指出, 要获得此行级锁之前, 需要预先获得的表级锁, 这里列出的是最低要求。

这六个行级锁的主要功能如下:

1. S锁:此行级锁的拥有者可以读取该行的信息;

2. U锁:此行级锁的拥有者可以读取该行的信息,如果要更新该行,则仍然需要一个行级的X锁;其他的应用只能读取该行的信息;此锁主要是用于FOR UPDATE的游标。

3. X锁:此行级锁的拥有者可以更新该行的纪录,其他的应用不能连接此行的信息;

4. W锁:此锁和X锁类似,不同之处是此锁和NW锁兼容;

5. NS锁:类似于S锁,用于Next Key;

6. NW锁:类似于W锁,用于Next Key;

在DB2数据库中, 是通过行级锁和表级锁协调作用来提供较好的并发性, 同时保证数据库中数据的安全。 在DB2中缺省情况下使用行级锁(当然需要IS/IX锁配合),只有当出现锁资源不足, 或者是用命令指定使用表级锁的情况下, 才会在应用连接中使用表级锁。 对锁资源分配有兴趣的读者可以参考DB2的管理手册, 查找其中关于locklist和maxlocks参数的论述。对于用命令指定表级锁的情况, 可以参考DB2的命令手册中的lock table命令, 此命令用于直接锁表。

隔离级别:

下面让我们来看一下隔离级别。 隔离级别主要用于控制在DB2根据应用提交的SQL语句向DB2数据库中的相应对象加锁时, 会锁住哪些纪录, 也就是锁定的范围。 隔离级别的不同, 锁定的纪录的范围可能会有很大的差别。

隔离级别分为RR/RS/CS/UR这四个级别。 下面让我们来逐一论述:

1. RR隔离级别: 在此隔离级别下, DB2会锁住所有相关的纪录。 在一个SQL语句执行期间, 所有执行此语句扫描过的纪录都会被加上相应的锁。 具体的锁的类型还是由操作的类型来决定, 如果是读取,则加共享锁; 如果是更新, 则加独占锁。 由于会锁定所有为获得SQL语句的结果而扫描的纪录, 所以锁的数量可能会很庞大, 这个时候, 索引的增加可能会对SQL语句的执行有很大的影响,因为索引会影响SQL语句扫描的纪录数量。

2. RS隔离级别: 此隔离级别的要求比RR隔离级别稍弱,此隔离级别下会锁定所有符合条件的纪录。 不论是读取, 还是更新, 如果SQL语句中包含查询条件, 则会对所有符合条件的纪录加相应的锁。 如果没有条件语句, 也就是对表中的所有记录进行处理,则会对所有的纪录加锁。

3. CS隔离级别: 此隔离级别仅锁住当前处理的纪录。

4. UR隔离级别:此隔离级别下,如果是读取操作,不会出现任何的行级锁。对于非只读的操作,它的锁处理和CS相同。

在这四种隔离级别中, CS是缺省值。 这四种隔离级别均可以保证DB2数据库在并发的环境下不会有数据丢失的情况发生。 要注意的是如果对纪录进行了修改,需要在相应的纪录上加独占类型的锁, 这些独占类型的锁直到交易结束时才会被释放, 这一点在四种隔离级别下都是相同的。

posted @ 2006-08-22 12:07 MyJavaWorld 阅读(866) | 评论 (0)编辑 收藏

REORG TABLE

REORG TABLE 语句压缩与指定的表相关联的数据。

调用

此语句可以在使用 DB2 CLI 函数的应用程序中使用,也可以通过 CLP 发出。

语法

>>-REORG TABLE--table-name--+------------+---------------------><
                            '-int1--int2-'
 
 

描述

REORG TABLE table-name
标识重组操作的表。名称必须标识现有的表。
int1
需要恢复的字节的可选最小百分比。
int2
需要为将要执行的表压缩恢复的最小字节数。

规则

  • 可选的值 int1int2 必须一起使用,或全都不用。
  • 可选的值 int1 必须是非负数。
  • 可选的值 int1 必须介于 0 与 100 之间。

注意事项

  • DB2 Everyplace 可以以内部方式调用表重组。
  • 第一个可选参数是表必须包含的不可用的字节的百分比(即百分之十(10)意味“至少百分之十的空间不可用”。)第二个可选参数是表必须包含的不可用的字节数(即 1000 将意味“至少 1000 个字节必须是不可用的空间”。)必须符合两个条件,才可以进行表的实际重组。
  • 如果没有指定参数,DB2 Everyplace 对这此选项使用缺省值。缺省百分比是 30 且缺省字节是 6144。因此,“reorg table t1”与“reorg table t1 30 6144”相同。
  • 如果重组方式设置为已启用,则 DB2 Everyplace 将自动重组表。如果在 DELETE 或 UPDATE 上启用了重组,则在执行语句之后,会对目标表执行“reorg table table_name 50 30270”。如果在 DROP TABLE 上启用了重组,则在删除表处理结束时执行“reorg table DB2eSYSTABLES 30 10240”(对于 DB2eSYSCOLUMNS 和 DB2eSYSRELS 也是如此)。
  • 在 C/C++ 程序中,通过使用具有属性 SQL_ATTR_REORG_MODE 的 CLI/ODBC 函数 SQLSetStmtAttr 设置重组方式。在 JAVA 程序中,通过 DB2eStatement 接口 enableReorg 方法设置重组方式。缺省值是启用重组。
  • 重组表时,通过物理上回收删除和更新创建的不可用空间来压缩包含表的数据文件。然后将表的索引更新为指向行的新物理位置。
  • 可以重组“DB2 Everyplace 系统目录”基本表。
  • 在执行 REORG TABLE 语句时,数据库中不应发生任何其它活动。

示例

使用缺省值压缩 VNNURSE 表。

REORG TABLE VNNURSE 
posted @ 2006-07-26 22:10 MyJavaWorld 阅读(868) | 评论 (0)编辑 收藏
     摘要: 在数据库应用程序中使用存储过程有许多好处,包括减少对网络的使用、提高性能以及降低开发成本。Java 存储过程是 DB2 支持的最流行的例程之一。原因之一是,由于 Java 编程语言非常流行,所以 Java 开发人员非常多。因此,在有多种语言可供选择时,Java 例程往往是首选的。 DB2 存储过程不一定非用 Java 来编写。如果业务逻辑只需要简单的存储过程,那么可以考虑用 ...  阅读全文
posted @ 2006-07-21 10:03 MyJavaWorld 阅读(5582) | 评论 (0)编辑 收藏

J***A正则表达式

关键词正则表达式                                          

正则表达式

。正则表达式(regular expression)是JDK 1.4的新功能,但是对sed和awk这样的Unix的标准实用工具,以及Python,Perl之类的语言来讲,它早就已经成为其不可或缺的组成部分了(有人甚至认为,它还是Perl能大获成功的最主要的原因)。单从技术角度来讲,正则表达式只是一种处理字符串的工具(过去Java这个任务是交由StringStringBuffer以及StringTokenizer处理的),但是它常常和I/O一起使用,所以放到这里来讲也不算太离题吧。

正则表达式是一种功能强大但又非常灵活的文本处理工具。它能让你用编程的方式来描述复杂的文本模式,然后在字符串里把它找出来。一旦你找到了这种模式,你就能随心所欲地处理这些文本了。虽然初看起来正则表达式的语法有点让人望而生畏,但它提供了一种精练的动态语言,使我们能用一种通用的方式来解决各种字符串的问题,包括匹配,选择,编辑以及校验。

创建正则表达式

你可以从比较简单的东西入手学习正则表达式。要想全面地掌握怎样构建正则表达式,可以去看JDK文档的java.util.regexPattern类的文档。

字符
B字符B
\xhh16进制值0xhh所表示的字符
\uhhhh16进制值0xhhhh所表示的Unicode字符
\tTab
\n换行符
\r回车符
\f换页符
\eEscape

正则表达式的强大体现在它能定义字符集(character class)。下面是一些最常见的字符集及其定义的方式,此外还有一些预定义的字符集:

字符集
.表示任意一个字符
[abc]表示字符abc中的任意一个(与a|b|c相同)
[^abc]abc之外的任意一个字符(否定)
[a-zA-Z]azAZ当中的任意一个字符(范围)
[abc[hij]]a,b,c,h,i,j中的任意一个字符(与a|b|c|h|i|j相同)(并集)
[a-z&&[hij]]h,i,j中的一个(交集)
\s空格字符(空格键, tab, 换行, 换页, 回车)
\S非空格字符([^\s])
\d一个数字,也就是[0-9]
\D一个非数字的字符,也就是[^0-9]
\w一个单词字符(word character),即[a-zA-Z_0-9]
\W一个非单词的字符,[^\w]

如果你用过其它语言的正则表达式,那么你一眼就能看出反斜杠的与众不同。在其它语言里,"\\"的意思是"我只是要在正则表达式里插入一个反斜杠。没什么特别的意思。"但是在Java里,"\\"的意思是"我要插入一个正则表达式的反斜杠,所以跟在它后面的那个字符的意思就变了。"举例来说,如果你想表示一个或更多的"单词字符",那么这个正则表达式就应该是"\\w+"。如果你要插入一个反斜杠,那就得用"\\\\"。不过像换行,跳格之类的还是只用一根反斜杠:"\n\t"。

这里只给你讲一个例子;你应该JDK文档的java.util.regex.Pattern加到收藏夹里,这样就能很容易地找到各种正则表达式的模式了。

逻辑运算符
XYX 后面跟着 Y
X|YX或Y
(X)一个"要匹配的组(capturing group)". 以后可以用\i来表示第i个被匹配的组。

边界匹配符
^一行的开始
$一行的结尾
\b一个单词的边界
\B一个非单词的边界
\G前一个匹配的结束

举一个具体一些的例子。下面这些正则表达式都是合法的,而且都能匹配"Rudolph":

Rudolph
[rR]udolph
[rR][aeiou][a-z]ol.*
R.*

数量表示符

"数量表示符(quantifier)"的作用是定义模式应该匹配多少个字符。

  • Greedy(贪婪的): 除非另有表示,否则数量表示符都是greedy的。Greedy的表达式会一直匹配下去,直到匹配不下去为止。(如果你发现表达式匹配的结果与预期的不符),很有可能是因为,你以为表达式会只匹配前面几个字符,而实际上它是greedy的,因此会一直匹配下去。
  • Reluctant(勉强的): 用问号表示,它会匹配最少的字符。也称为lazy, minimal matching, non-greedy, 或ungreedy。
  • Possessive(占有的): 目前只有Java支持(其它语言都不支持)。它更加先进,所以你可能还不太会用。用正则表达式匹配字符串的时候会产生很多中间状态,(一般的匹配引擎会保存这种中间状态,)这样匹配失败的时候就能原路返回了。占有型的表达式不保存这种中间状态,因此也就不会回头重来了。它能防止正则表达式的失控,同时也能提高运行的效率。
GreedyReluctantPossessive匹配
X?X??X?+匹配一个或零个X
X*X*?X*+匹配零或多个X
X+X+?X++匹配一个或多个X
X{n}X{n}?X{n}+匹配正好n个X
X{n,}X{n,}?X{n,}+匹配至少n个X
X{n,m}X{n,m}?X{n,m}+匹配至少n个,至多m个X

再提醒一下,要想让表达式照你的意思去运行,你应该用括号把'X'括起来。比方说:

abc+

似乎这个表达式能匹配一个或若干个'abc',但是如果你真的用它去匹配'abcabcabc'的话,实际上只会找到三个字符。因为这个表达式的意思是'ab'后边跟着一个或多个'c'。要想匹配一个或多个完整的'abc',你应该这样:

(abc)+

正则表达式能轻而易举地把你给耍了;这是一种建立在Java之上的新语言。

CharSequence

JDK 1.4定义了一个新的接口,叫CharSequence。它提供了StringStringBuffer这两个类的字符序列的抽象:

interface CharSequence {
  charAt(int i);
  length();
  subSequence(int start, int end);
  toString();
}

为了实现这个新的CharSequence接口,StringStringBuffer以及CharBuffer都作了修改。很多正则表达式的操作都要拿CharSequence作参数。

PatternMatcher

先给一个例子。下面这段程序可以测试正则表达式是否匹配字符串。第一个参数是要匹配的字符串,后面是正则表达式。正则表达式可以有多个。在Unix/Linux环境下,命令行下的正则表达式还必须用引号。

当你创建正则表达式时,可以用这个程序来判断它是不是会按照你的要求工作。

//: c12:TestRegularExpression.java// Allows you to easly try out regular expressions.// {Args: abcabcabcdefabc "abc+" "(abc)+" "(abc){2,}" }import java.util.regex.*;
publicclass TestRegularExpression {
  publicstaticvoid main(String[] args) {
    if(args.length < 2) {
      System.out.println("Usage:\n" +
        "java TestRegularExpression " +
        "characterSequence regularExpression+");
      System.exit(0);
    }
    System.out.println("Input: \"" + args[0] + "\"");
    for(int i = 1; i < args.length; i++) {
      System.out.println(
        "Regular expression: \"" + args[i] + "\"");
      Pattern p = Pattern.compile(args[i]);
      Matcher m = p.matcher(args[0]);
      while(m.find()) {
        System.out.println("Match \"" + m.group() +
          "\" at positions " +
          m.start() + "-" + (m.end() - 1));
      }
    }
  }
} ///:~

Java的正则表达式是由java.util.regexPatternMatcher类实现的。Pattern对象表示经编译的正则表达式。静态的compile( )方法负责将表示正则表达式的字符串编译成Pattern对象。正如上述例程所示的,只要给Patternmatcher( )方法送一个字符串就能获取一个Matcher对象。此外,Pattern还有一个能快速判断能否在input里面找到regex的(注意,原文有误,漏了方法名)

staticboolean matches( regex,  input)

以及能返回String数组的split( )方法,它能用regex把字符串分割开来。

只要给Pattern.matcher( )方法传一个字符串就能获得Matcher对象了。接下来就能用Matcher的方法来查询匹配的结果了。

boolean matches()
boolean lookingAt()
boolean find()
boolean find(int start)

matches( )的前提是Pattern匹配整个字符串,而lookingAt( )的意思是Pattern匹配字符串的开头。

find( )

Matcher.find( )的功能是发现CharSequence里的,与pattern相匹配的多个字符序列。例如:

//: c12:FindDemo.javaimport java.util.regex.*;
import com.bruceeckel.simpletest.*;
import java.util.*;
publicclass FindDemo {
  privatestatic Test monitor = new Test();
  publicstaticvoid main(String[] args) {
    Matcher m = Pattern.compile("\\w+")
      .matcher("Evening is full of the linnet's wings");
    while(m.find())
      System.out.println(m.group());
    int i = 0;
    while(m.find(i)) {
      System.out.print(m.group() + " ");
      i++;
    }
    monitor.expect(new String[] {
      "Evening",
      "is",
      "full",
      "of",
      "the",
      "linnet",
      "s",
      "wings",
      "Evening vening ening ning ing ng g is is s full " +
      "full ull ll l of of f the the he e linnet linnet " +
      "innet nnet net et t s s wings wings ings ngs gs s "
    });
  }
} ///:~

"\\w+"的意思是"一个或多个单词字符",因此它会将字符串直接分解成单词。find( )像一个迭代器,从头到尾扫描一遍字符串。第二个find( )是带int参数的,正如你所看到的,它会告诉方法从哪里开始找——即从参数位置开始查找。

Groups

Group是指里用括号括起来的,能被后面的表达式调用的正则表达式。Group 0 表示整个表达式,group 1表示第一个被括起来的group,以此类推。所以;

A(B(C))D

里面有三个group:group 0是ABCD, group 1是BC,group 2是C

你可以用下述Matcher方法来使用group:

public int groupCount( )返回matcher对象中的group的数目。不包括group0。

public String group( ) 返回上次匹配操作(比方说find( ))的group 0(整个匹配)

public String group(int i)返回上次匹配操作的某个group。如果匹配成功,但是没能找到group,则返回null。

public int start(int group)返回上次匹配所找到的,group的开始位置。

public int end(int group)返回上次匹配所找到的,group的结束位置,最后一个字符的下标加一。

下面我们举一些group的例子:

//: c12:Groups.javaimport java.util.regex.*;
import com.bruceeckel.simpletest.*;
publicclass Groups {
  privatestatic Test monitor = new Test();
  staticpublicfinal String poem =
    "Twas brillig, and the slithy toves\n" +
    "Did gyre and gimble in the wabe.\n" +
    "All mimsy were the borogoves,\n" +
    "And the mome raths outgrabe.\n\n" +
    "Beware the Jabberwock, my son,\n" +
    "The jaws that bite, the claws that catch.\n" +
    "Beware the Jubjub bird, and shun\n" +
    "The frumious Bandersnatch.";
  publicstaticvoid main(String[] args) {
    Matcher m =
      Pattern.compile("(?m)(\\S+)\\s+((\\S+)\\s+(\\S+))$")
        .matcher(poem);
    while(m.find()) {
      for(int j = 0; j <= m.groupCount(); j++)
        System.out.print("[" + m.group(j) + "]");
      System.out.println();
    }
    monitor.expect(new String[]{
      "[the slithy toves]" +
      "[the][slithy toves][slithy][toves]",
      "[in the wabe.][in][the wabe.][the][wabe.]",
      "[were the borogoves,]" +
      "[were][the borogoves,][the][borogoves,]",
      "[mome raths outgrabe.]" +
      "[mome][raths outgrabe.][raths][outgrabe.]",
      "[Jabberwock, my son,]" +
      "[Jabberwock,][my son,][my][son,]",
      "[claws that catch.]" +
      "[claws][that catch.][that][catch.]",
      "[bird, and shun][bird,][and shun][and][shun]",
      "[The frumious Bandersnatch.][The]" +
      "[frumious Bandersnatch.][frumious][Bandersnatch.]"
    });
  }
} ///:~

这首诗是Through the Looking Glass的,Lewis Carroll的"Jabberwocky"的第一部分。可以看到这个正则表达式里有很多用括号括起来的group,它是由任意多个连续的非空字符('\S+')和任意多个连续的空格字符('\s+')所组成的,其最终目的是要捕获每行的最后三个单词;'$'表示一行的结尾。但是'$'通常表示整个字符串的结尾,所以这里要明确地告诉正则表达式注意换行符。这一点是由'(?m)'标志完成的(模式标志会过一会讲解)。

start( )和end( )

如果匹配成功,start( )会返回此次匹配的开始位置,end( )会返回此次匹配的结束位置,即最后一个字符的下标加一。如果之前的匹配不成功(或者没匹配),那么无论是调用start( )还是end( ),都会引发一个IllegalStateException。下面这段程序还演示了matches( )lookingAt( )

//: c12:StartEnd.javaimport java.util.regex.*;
import com.bruceeckel.simpletest.*;
publicclass StartEnd {
  privatestatic Test monitor = new Test();
  publicstaticvoid main(String[] args) {
    String[] input = new String[] {
      "Java has regular expressions in 1.4",
      "regular expressions now expressing in Java",
      "Java represses oracular expressions"
    };
    Pattern
      p1 = Pattern.compile("re\\w*"),
      p2 = Pattern.compile("Java.*");
    for(int i = 0; i < input.length; i++) {
      System.out.println("input " + i + ": " + input[i]);
      Matcher
        m1 = p1.matcher(input[i]),
        m2 = p2.matcher(input[i]);
      while(m1.find())
        System.out.println("m1.find() '" + m1.group() +
          "' start = "+ m1.start() + " end = " + m1.end());
      while(m2.find())
        System.out.println("m2.find() '" + m2.group() +
          "' start = "+ m2.start() + " end = " + m2.end());
      if(m1.lookingAt()) // No reset() necessary
        System.out.println("m1.lookingAt() start = "
          + m1.start() + " end = " + m1.end());
      if(m2.lookingAt())
        System.out.println("m2.lookingAt() start = "
          + m2.start() + " end = " + m2.end());
      if(m1.matches()) // No reset() necessary
        System.out.println("m1.matches() start = "
          + m1.start() + " end = " + m1.end());
      if(m2.matches())
        System.out.println("m2.matches() start = "
          + m2.start() + " end = " + m2.end());
    }
    monitor.expect(new String[] {
      "input 0: Java has regular expressions in 1.4",
      "m1.find() 'regular' start = 9 end = 16",
      "m1.find() 'ressions' start = 20 end = 28",
      "m2.find() 'Java has regular expressions in 1.4'" +
      " start = 0 end = 35",
      "m2.lookingAt() start = 0 end = 35",
      "m2.matches() start = 0 end = 35",
      "input 1: regular expressions now " +
      "expressing in Java",
      "m1.find() 'regular' start = 0 end = 7",
      "m1.find() 'ressions' start = 11 end = 19",
      "m1.find() 'ressing' start = 27 end = 34",
      "m2.find() 'Java' start = 38 end = 42",
      "m1.lookingAt() start = 0 end = 7",
      "input 2: Java represses oracular expressions",
      "m1.find() 'represses' start = 5 end = 14",
      "m1.find() 'ressions' start = 27 end = 35",
      "m2.find() 'Java represses oracular expressions' " +
      "start = 0 end = 35",
      "m2.lookingAt() start = 0 end = 35",
      "m2.matches() start = 0 end = 35"
    });
  }
} ///:~

注意,只要字符串里有这个模式,find( )就能把它给找出来,但是lookingAt( )matches( ),只有在字符串与正则表达式一开始就相匹配的情况下才能返回truematches( )成功的前提是正则表达式与字符串完全匹配,而lookingAt( )[67]成功的前提是,字符串的开始部分与正则表达式相匹配。

匹配的模式(Pattern flags)

compile( )方法还有一个版本,它需要一个控制正则表达式的匹配行为的参数:

Pattern Pattern.compile(String regex, int flag)
flag的取值范围如下:
编译标志效果
Pattern.CANON_EQ当且仅当两个字符的"正规分解(canonical decomposition)"都完全相同的情况下,才认定匹配。比如用了这个标志之后,表达式"a\u030A"会匹配"?"。默认情况下,不考虑"规范相等性(canonical equivalence)"。
Pattern.CASE_INSENSITIVE
(?i)
默认情况下,大小写不明感的匹配只适用于US-ASCII字符集。这个标志能让表达式忽略大小写进行匹配。要想对Unicode字符进行大小不明感的匹配,只要将UNICODE_CASE与这个标志合起来就行了。
Pattern.COMMENTS
(?x)
在这种模式下,匹配时会忽略(正则表达式里的)空格字符(译者注:不是指表达式里的"\\s",而是指表达式里的空格,tab,回车之类)。注释从#开始,一直到这行结束。可以通过嵌入式的标志来启用Unix行模式。
Pattern.DOTALL
(?s)
在这种模式下,表达式'.'可以匹配任意字符,包括表示一行的结束符。默认情况下,表达式'.'不匹配行的结束符。
Pattern.MULTILINE
(?m)
在这种模式下,'^'和'$'分别匹配一行的开始和结束。此外,'^'仍然匹配字符串的开始,'$'也匹配字符串的结束。默认情况下,这两个表达式仅仅匹配字符串的开始和结束。
Pattern.UNICODE_CASE
(?u)
在这个模式下,如果你还启用了CASE_INSENSITIVE标志,那么它会对Unicode字符进行大小写不明感的匹配。默认情况下,大小写不明感的匹配只适用于US-ASCII字符集。
Pattern.UNIX_LINES
(?d)
在这个模式下,只有'\n'才被认作一行的中止,并且与'.','^',以及'$'进行匹配。

在这些标志里面,Pattern.CASE_INSENSITIVEPattern.MULTILINE,以及Pattern.COMMENTS是最有用的(其中Pattern.COMMENTS还能帮我们把思路理清楚,并且/或者做文档)。注意,你可以用在表达式里插记号的方式来启用绝大多数的模式。这些记号就在上面那张表的各个标志的下面。你希望模式从哪里开始启动,就在哪里插记号。

可以用"OR" ('|')运算符把这些标志合使用:

//: c12:ReFlags.javaimport java.util.regex.*;
import com.bruceeckel.simpletest.*;
publicclass ReFlags {
  privatestatic Test monitor = new Test();
  publicstaticvoid main(String[] args) {
    Pattern p =  Pattern.compile("^java",
      Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
    Matcher m = p.matcher(
      "java has regex\nJava has regex\n" +
      "J***A has pretty good regular expressions\n" +
      "Regular expressions are in Java");
    while(m.find())
      System.out.println(m.group());
    monitor.expect(new String[] {
      "java",
      "Java",
      "J***A"
    });
  }
} ///:~

这样创建出来的正则表达式就能匹配以"java","Java","J***A"...开头的字符串了。此外,如果字符串分好几行,那它还会对每一行做匹配(匹配始于字符序列的开始,终于字符序列当中的行结束符)。注意,group( )方法仅返回匹配的部分。

split( )

所谓分割是指将以正则表达式为界,将字符串分割成String数组。

String[] split(CharSequence charseq)
String[] split(CharSequence charseq, int limit)

这是一种既快又方便地将文本根据一些常见的边界标志分割开来的方法。

//: c12:SplitDemo.javaimport java.util.regex.*;
import com.bruceeckel.simpletest.*;
import java.util.*;
publicclass SplitDemo {
  privatestatic Test monitor = new Test();
  publicstaticvoid main(String[] args) {
    String input =
      "This!!unusual use!!of exclamation!!points";
    System.out.println(Arrays.asList(
      Pattern.compile("!!").split(input)));
    // Only do the first three:
    System.out.println(Arrays.asList(
      Pattern.compile("!!").split(input, 3)));
    System.out.println(Arrays.asList(
      "Aha! String has a split() built in!".split(" ")));
    monitor.expect(new String[] {
      "[This, unusual use, of exclamation, points]",
      "[This, unusual use, of exclamation!!points]",
      "[Aha!, String, has, a, split(), built, in!]"
    });
  }
} ///:~

第二个split( )会限定分割的次数。

正则表达式是如此重要,以至于有些功能被加进了String类,其中包括split( )(已经看到了),matches( )replaceFirst( )以及replaceAll( )。这些方法的功能同PatternMatcher的相同。

替换操作

正则表达式在替换文本方面特别在行。下面就是一些方法:

replaceFirst(String replacement)将字符串里,第一个与模式相匹配的子串替换成replacement

replaceAll(String replacement),将输入字符串里所有与模式相匹配的子串全部替换成replacement

appendReplacement(StringBuffer sbuf, String replacement)sbuf进行逐次替换,而不是像replaceFirst( )replaceAll( )那样,只替换第一个或全部子串。这是个非常重要的方法,因为它可以调用方法来生成replacement(replaceFirst( )replaceAll( )只允许用固定的字符串来充当replacement)。有了这个方法,你就可以编程区分group,从而实现更强大的替换功能。

调用完appendReplacement( )之后,为了把剩余的字符串拷贝回去,必须调用appendTail(StringBuffer sbuf, String replacement)

下面我们来演示一下怎样使用这些替换方法。说明一下,这段程序所处理的字符串是它自己开头部分的注释,是用正则表达式提取出来并加以处理之后再传给替换方法的。

//: c12:TheReplacements.javaimport java.util.regex.*;
import java.io.*;
import com.bruceeckel.util.*;
import com.bruceeckel.simpletest.*;
/*! Here's a block of text to use as input to
    the regular expression matcher. Note that we'll
    first extract the block of text by looking for
    the special delimiters, then process the
    extracted block. !*/publicclass TheReplacements {
  privatestatic Test monitor = new Test();
  publicstaticvoid main(String[] args) throws Exception {
    String s = TextFile.read("TheReplacements.java");
    // Match the specially-commented block of text above:
    Matcher mInput =
      Pattern.compile("/\\*!(.*)!\\*/", Pattern.DOTALL)
        .matcher(s);
    if(mInput.find())
      s = mInput.group(1); // Captured by parentheses// Replace two or more spaces with a single space:
    s = s.replaceAll(" {2,}", " ");
    // Replace one or more spaces at the beginning of each// line with no spaces. Must enable MULTILINE mode:
    s = s.replaceAll("(?m)^ +", "");
    System.out.println(s);
    s = s.replaceFirst("[aeiou]", "(VOWEL1)");
    StringBuffer sbuf = new StringBuffer();
    Pattern p = Pattern.compile("[aeiou]");
    Matcher m = p.matcher(s);
    // Process the find information as you// perform the replacements:while(m.find())
      m.appendReplacement(sbuf, m.group().toUpperCase());
    // Put in the remainder of the text:
    m.appendTail(sbuf);
    System.out.println(sbuf);
    monitor.expect(new String[]{
      "Here's a block of text to use as input to",
      "the regular expression matcher. Note that we'll",
      "first extract the block of text by looking for",
      "the special delimiters, then process the",
      "extracted block. ",
      "H(VOWEL1)rE's A blOck Of tExt tO UsE As InpUt tO",
      "thE rEgUlAr ExprEssIOn mAtchEr. NOtE thAt wE'll",
      "fIrst ExtrAct thE blOck Of tExt by lOOkIng fOr",
      "thE spEcIAl dElImItErs, thEn prOcEss thE",
      "ExtrActEd blOck. "
    });
  }
} ///:~

我们用前面介绍的TextFile.read( )方法来打开和读取文件。mInput的功能是匹配'/*!' 和 '!*/' 之间的文本(注意一下分组用的括号)。接下来,我们将所有两个以上的连续空格全都替换成一个,并且将各行开头的空格全都去掉(为了让这个正则表达式能对所有的行,而不仅仅是第一行起作用,必须启用多行模式)。这两个操作都用了StringreplaceAll( )(这里用它更方便)。注意,由于每个替换只做一次,因此除了预编译Pattern之外,程序没有额外的开销。

replaceFirst( )只替换第一个子串。此外,replaceFirst( )replaceAll( )只能用常量(literal)来替换,所以如果你每次替换的时候还要进行一些操作的话,它们是无能为力的。碰到这种情况,你得用appendReplacement( ),它能让你在进行替换的时候想写多少代码就写多少。在上面那段程序里,创建sbuf的过程就是选group做处理,也就是用正则表达式把元音字母找出来,然后换成大写的过程。通常你得在完成全部的替换之后才调用appendTail( ),但是如果要模仿replaceFirst( )(或"replace n")的效果,你也可以只替换一次就调用appendTail( )。它会把剩下的东西全都放进sbuf

你还可以在appendReplacement( )replacement参数里用"$g"引用已捕获的group,其中'g' 表示group的号码。不过这是为一些比较简单的操作准备的,因而其效果无法与上述程序相比。

reset( )

此外,还可以用reset( )方法给现有的Matcher对象配上个新的CharSequence

//: c12:Resetting.javaimport java.util.regex.*;
import java.io.*;
import com.bruceeckel.simpletest.*;
publicclass Resetting {
  privatestatic Test monitor = new Test();
  publicstaticvoid main(String[] args) throws Exception {
    Matcher m = Pattern.compile("[frb][aiu][gx]")
      .matcher("fix the rug with bags");
    while(m.find())
      System.out.println(m.group());
    m.reset("fix the rig with rags");
    while(m.find())
      System.out.println(m.group());
    monitor.expect(new String[]{
      "fix",
      "rug",
      "bag",
      "fix",
      "rig",
      "rag"
    });
  }
} ///:~

如果不给参数,reset( )会把Matcher设到当前字符串的开始处。

正则表达式与Java I/O

到目前为止,你看到的都是用正则表达式处理静态字符串的例子。下面我们来演示一下怎样用正则表达式扫描文件并且找出匹配的字符串。受Unix的grep启发,我写了个JGrep.java,它需要两个参数:文件名,以及匹配字符串用的正则表达式。它会把匹配这个正则表达式那部分内容及其所属行的行号打印出来。

//: c12:JGrep.java// A very simple version of the "grep" program.// {Args: JGrep.java "\\b[Ssct]\\w+"}import java.io.*;
import java.util.regex.*;
import java.util.*;
import com.bruceeckel.util.*;
publicclass JGrep {
  publicstaticvoid main(String[] args) throws Exception {
    if(args.length < 2) {
      System.out.println("Usage: java JGrep file regex");
      System.exit(0);
    }
    Pattern p = Pattern.compile(args[1]);
    // Iterate through the lines of the input file:
    ListIterator it = new TextFile(args[0]).listIterator();
    while(it.hasNext()) {
      Matcher m = p.matcher((String)it.next());
      while(m.find())
        System.out.println(it.nextIndex() + ": " +
          m.group() + ": " + m.start());
    }
  }
} ///:~

文件是用TextFile打开的(本章的前半部分讲的)。由于TextFile会把文件的各行放在ArrayList里面,而我们又提取了一个ListIterator,因此我们可以在文件的各行当中自由移动(既能向前也可以向后)。

每行都会有一个Matcher,然后用find( )扫描。注意,我们用ListIterator.nextIndex( )跟踪行号。

测试参数是JGrep.java和以[Ssct]开头的单词。

还需要StringTokenizer吗?

看到正则表达式能提供这么强大的功能,你可能会怀疑,是不是还需要原先的StringTokenizer。JDK 1.4以前,要想分割字符串,只有用StringTokenizer。但现在,有了正则表达式之后,它就能做得更干净利索了。

//: c12:ReplacingStringTokenizer.javaimport java.util.regex.*;
import com.bruceeckel.simpletest.*;
import java.util.*;
publicclass ReplacingStringTokenizer {
  privatestatic Test monitor = new Test();
  publicstaticvoid main(String[] args) {
    String input = "But I'm not dead yet! I feel happy!";
    StringTokenizer stoke = new StringTokenizer(input);
    while(stoke.hasMoreElements())
      System.out.println(stoke.nextToken());
    System.out.println(Arrays.asList(input.split(" ")));
    monitor.expect(new String[] {
      "But",
      "I'm",
      "not",
      "dead",
      "yet!",
      "I",
      "feel",
      "happy!",
      "[But, I'm, not, dead, yet!, I, feel, happy!]"
    });
  }
} ///:~

有了正则表达式,你就能用更复杂的模式将字符串分割开来——要是交给StringTokenizer的话,事情会麻烦得多。我可以很有把握地说,正则表达式可以取代StringTokenizer

要想进一步学习正则表达式,建议你看Mastering Regular Expression, 2nd Edition,作者Jeffrey E. F. Friedl (O’Reilly, 2002)。

总结

Java的I/O流类库应该能满足你的基本需求:你可以用它来读写控制台,文件,内存,甚至是Internet。你还可以利用继承来创建新的输入和输出类型。你甚至可以利用Java会自动调用对象的toString( )方法的特点(Java仅有的"自动类型转换"),通过重新定义这个方法,来对要传给流的对象做一个简单的扩展。

但是Java的I/O流类库及其文档还是留下了一些缺憾。比方说你打开一个文件往里面写东西,但是这个文件已经有了,这么做会把原先的内容给覆盖了 。这时要是能有一个异常就好了——有些编程语言能让你规定只能往新建的文件里输出。看来Java是要你用File对象来判断文件是否存在,因为如果你用FileOutputStreamFileWriter的话,文件就会被覆盖了。

我对I/O流类库的评价是比较矛盾的;它确实能干很多事情,而且做到了跨平台。但是如果你不懂decorator模式,就会觉得这种设计太难理解了,所以无论是对老师还是学生,都得多花精力。此外这个类库也不完整,否则我也用不着去写TextFile了。此外它没有提供格式化输出的功能,而其他语言都已经提供了这种功能。

posted @ 2006-07-20 15:48 MyJavaWorld 阅读(307) | 评论 (0)编辑 收藏