DB2 常用命令参考

合集下载

DB2常用命令

DB2常用命令

db2 常用命令 2011-06-19 09:59:35分类: Linuxdb2常用命令大全db2跟Oracle相比一些命令有很大的区别,而它最大的功能是支持xml存储、检索机制,通过XPath进行解析操作,使开发人员免于对xml文件在应用进行解析处理,先对其常用命令进行一下汇总,以免遗忘。

注意:在执行如下命令时,需要首先安装db2客户端并通过在运行中输入db2cmd进行初始化一、基础篇1、db2 connect to <数据库名> --连接到本地数据库名db2 connect to <数据库名> user <用户名> using <密码> --连接到远端数据库2、 db2 force application all --强迫所有应用断开数据库连接3、db2 backup db db2name<数据库名称> --备份整个数据库数据db2 restore db --还原数据库4、db2 list application --查看所有连接(需要连接到具体数据库才能查看)5、db2start --启动数据库db2stop --停止数据库6、create database <数据库名> using codeset utf-8 territory CN --创建数据库使用utf-8编码7、db2 catalog 命令db2 catalog tcpip node <接点名称> remote <远程数据库地址> server <端口号> --把远程数据库映射到本地接点一般为50000db2 catalog db <远程数据库名称> as <接点名称> at node PUB11 --远程数据库名称到本地接点db2 CONNECT TO <接点名称> user <用户名> using <密码> --连接本地接点访问远程数据库8、数据库导出db2look -d <数据库名> -u <用户> -e -o <脚本名称>.sql --导出数据库的表结构,其中用户空间一般为db2admin/db2inst1db2look -d <数据库名> -u <用户> -t <表1> <表2> -e -o <脚本名称>.sql --导出数据库中表1和表2的表结构db2move <数据库名> export --导出数据库数据db2move <数据库名> export -tn <表1>,<表2> --导出数据库中表和表数据9、数据库导入db2 -tvf <脚本名称>.sql --把上述导出的表结构导入到数据库表结构db2move <数据库名> load -lo replace --把上述“db2move <数据库名>export “导出的数据导入到数据库中并把相同的数据替换掉在实际使用过程中,如果用到db2自增主键,需要使用by default,而不是always,功能是一样的,但这样在数据移植时候会很方便!10、db2 connect reset 或 db2 terminate --断开与数据库的连接11、db2set db2codepage=1208 --修改页编码为120812、db2 describe table <表名> --查看表结构13、db2 list tables --查看数据库中所有表结构list tables for system --列出所有系统表14、db2 list tablespaces --列出表空间二、高级篇15、fetch first 10 rows only --列出表中前10条数据例如:select * from。

常用的db2命令

常用的db2命令

常用的db2命令启动数据库:启动db2服务:db2start 激活数据库实例:db2 activate database <db_name> 查看激活状态的数据库:db2 list active databases关闭数据库:失效数据库实例:db2 deactivate database <db_name> 关闭数据库服务:db2stop查看数据库:db2 list db directory查看数据库应用:db2 list applications 查看数据库应用和进程号:db2 list applications show detail 查看数据库表空间:db2pd -db <db_name> -tablespace查看数据库配置:db2 get db cfg for <db_name> 连接数据库:db2 connect to <db_name> db2 connect to <db_name> user[user_name] using [password] 断开数据库连接:db2 connect reset/db2 terminate 创建数据库:db2 create db <db_name> 删除数据库:db2 drop database <db_name> (如果不能删除,尝试断开激活的连接或者重启db2)列出系统表:db2 list tables for system 列出所有用户表:db2 list tables 列出所有表:db2 list tables for all 列出特定用户表:db2 list tables for schema [user]复制一张表:db2 create table t1 like t2 显示表结构:db2 describe table tablename 查询表:db2 "select * from table tablename where ..." 执行SQL脚本:db2 -tvf scripts.sql查看错误代码信息:db2 ? 10054 停止激活的连接:db2 force application all;\db2 force application all;\db2 force application all;\db2stop 查看死锁:db2 get snapshot for locks on <db_name> db2 "select agent_id,tabname,lock_mode from table(snap_get_lock('<db_name>')) as aa" 杀掉进程:db2 force application(NUM) 监控DB2消耗多的SQL语句:eg:(DB_NAME=CMSDB)db2top -d CMSDB -----查看消耗资源按照提示按l,出现Application Handle,找到资源消耗大的Application Handle(stat)记下app handle。

db2 常用命令

db2 常用命令

db2 常用命令db2 常用命令1. db2 "get dbm cfg" ——获取当前数据库配置信息。

2. db2 list db directory ——列出数据库的目录。

3. db2 list node directory ——列出节点的目录。

4. db2 "start database <dbname>" ——启动指定的数据库。

5. db2 "stop database <dbname>" ——停止指定的数据库。

6. db2 "connect to <dbname>" ——连接到指定的数据库。

7. db2 "update dbm cfg using max application <number>" ——修改数据库最大连接数。

8. db2 list active databases ——列出所有活动的数据库。

9. db2 get snapshot for dynamic sql on <database> ——列出动态SQL的快照。

10. db2 terminate ——立即终止当前会话。

11. db2 "create database <dbname>" ——创建新的数据库。

12. db2 connect reset ——重置数据库连接。

13. db2 "list tables" ——列出表格列表。

14. db2 "describe table <tablename>" ——查看表格结构。

15. db2 "select * from <tablename>" ——查询指定表格的信息。

16. db2 "drop table <tablename>" ——删除指定的表格。

DB2常用命令

DB2常用命令

Chapter 1.实例DB2 实例(instance)是DB2 可执行文件和您创建的任何DB2 数据库的逻辑资源库。

一台机器可以包含一个或多个实例,一个实例可以包含一个或多个数据库。

实例所使用的DB2 可执行文件和库包含在名为SQLLIB 的目录。

创建DB2 实例(root执行)#/opt/IBM/db2/V8.1/instance/db2icrt -u fenced_user_ID db2inst2db2ilist 命令列出机器上的DB2 实例。

$ db2ilistdb2inst1db2inst2查看当前使用的实例$ echo $DB2INSTANCEdb2inst1$db2 get instanceThe current database manager instance is: db2inst1删除实例(root执行)#/opt/IBM/db2/V8.1/instance/db2idrop db2inst2实例的启动和停止db2start 命令启动实例db2stop 命令停止实例Chapter 2.数据库建库实例CREATE DATABASE easydb ON /home/db2ese/space --保证全部建立在指定文件系统上CATALOG TABLESPACE --系统表空间MANAGED BY SYSTEM USING('/home/db2ese/space/catalog.dat') TEMPORARY TABLESPACE --系统临时表空间MANAGED BY DATABASE USING (FILE'/home/db2ese/space/tempspc' 1000)USER TABLESPACE --用户表空间MANAGED BY DATABASE USING(FILE '/home/db2ese/space/user1' 262144, --(1G=1*1024*1024/4 Pages)FILE '/home/db2ese/space/user2' 262144, FILE '/home/db2ese/space/user3' 262144 )DB2存储模型DMS 和SMS 表空间System Managed Space:SMS 表空间几乎不需要维护,这种折中潜在地降低了性能,并且减少了优化选项。

DB2命令大全

DB2命令大全
Db2 ? sql-204
1.12 备份数据库
备份表空间
Db2 “backup database databasename” tablespace tablespaceName to /path
Db2 backup database dbname to /path
db2 list db directory
1.16插入空值到表中
import from /dev/null of del replace into db2inst1.表名
1.17建立nickname
1、在db2命令窗口下,运行connect to 目标库 user 用户名 using 密码
Select stmt_text ,(stop_time-start_time) from stmt_ monitor_name Where stmt_operation not in (7,8,9,19) order by decimal(stop_time-start_time) desc fetch first 10 rows only
Lock Object Name = 1163533 #被锁对象名称
Object Type = Row #被锁对象类型
Tablespace Name = tbs_data #被锁对象所在的表空间
-LOCKTIMEOUT单位是秒,是锁等待最长时间,超过该时间仍未获得锁,则返回错误。
设置提示:
-缺省情况下,LOCKTIMEOUT是-1,意味着锁等待时间无限期,这和实际应用需求一般是不太相符的,需要将其值设为大于0的一个数。
-DLCHKTIME时间通常要设得比LOCKTIMEOUT时间小一些,否则未等发现死锁,就会被以锁等待超时而返回错误。

DB2命令

DB2命令

DB2命令一、常用命令1、建立数据库DB2_GCBCREATE DATABASE DB2_GCB ON G: ALIAS DB2_GCBUSING CODESET GBK TERRITORY CN COLLATE USING SYSTEM DFT_EXTENT_SZ 322、连接数据库connect to sample1 user db2admin using 83012063、建立用户、建立表别名create alias db2admin.tables for sysstat.tables;CREATE ALIAS DB2ADMIN.VIEWS FOR SYSCAT.VIEWScreate alias db2admin.columns for syscat.columns;create alias guest.columns for syscat.columns;GRANTDBADM,CREATETAB,BINDADD,CONNECT,CREATE_NOT_FENCED_ ROUTINE ON DATABASE TO USER GUEST;GRANT CREATEIN,DROPIN,ALTERIN ON SCHEMA DB2ADMIN TO USER GUEST WITH GRANT OPTION;4、建立、更改、删除表结构CREATE TABLE table_name(column1 DATATYPE [NOT NULL] [NOT NULL PRIMARY KEY], column2 DATATYPE [NOT NULL],...)create table zjt_tables as(select * from tables) definition only;create table zjt_views as(select * from views) definition only;ALTER TABLE table_name ADD COLUMN column_name DATATYPEALTER TABLE table_name ADD PRIMARY KEY (column_name)ALTER TABLE table_name DROP PRIMARY KEY (column_name)DROP table table_name5、插入记录,修改记录,删除记录insert into zjt_tables select * from tables;insert into zjt_views select * from views;insert into test(id,phone) values(1,’5’);update test set phone=’65356675’ where id=1;delete from test where id=1;6、建立视图create view V_zjt_tables as select tabschema,tabname from zjt_tables;7、建立触发器CREATE TRIGGER zjt_tables_delAFTER DELETE ON zjt_tablesREFERENCING OLD AS OFOR EACH ROW MODE DB2SQLInsert into zjt_tables1 values(substr(o.tabschema,1,8),substr(o.tabname,1,10))8、建立、删除唯一性索引CREATE UNIQUE INDEX I_ztables_tabnameON zjt_tables(tabname);DROP index I_ztables_tabname9、查看表select tabname from tableswhere tabname='ZJT_TABLES';10、查看列select SUBSTR(COLNAME,1,20) as 列名,TYPENAME as 类型,LENGTH as 长度from columnswhere tabname='ZJT_TABLES';11、查看表结构db2 describe table user1.departmentdb2 describe select * from user.tables12、查看表的索引db2 describe indexes for table user1.department13、查看视图select viewname from viewswhere viewname='V_ZJT_TABLES';14、查看索引select indname from indexeswhere indname='I_ZTABLES_TABNAME';15、查看存贮过程SELECTSUBSTR(PROCSCHEMA,1,15),SUBSTR(PROCNAME,1,15) FROM SYSCAT.PROCEDURES;16、类型转换(cast)ip datatype:varcharselect cast(ip as integer)+50 from log_comm_failed17、重新连接connect reset18、中断数据库连接disconnect db2_gcb19、view applicationLIST APPLICATION;20、kill applicationFORCE APPLICATION(0);db2 force applications all (强迫所有应用程序从数据库断开)21、lock tablelock table test in exclusive mode22、共享lock table test in share mode23、显示当前用户所有表list tables24、列出所有的系统表list tables for system25、显示当前活动数据库list active databases26、查看并设置命令选项list command optionsupdate command options using c off27、系统数据库目录LIST DATABASE DIRECTORY28、表空间list tablespacesCREATE [{REGULAR | LARGE | SYSTEM TEMPORARY | USER TEMPORARY}] TABLESPACE table_space_name [PAGESIZE integer [K]]MANAGED BY {SYSTEM | DATABASE}USING (container_definition_string) [BUFFERPOOL buffpool_name]29、表空间容器LIST TABLESPACE CONTAINERS FORExample: LIST TABLESPACE CONTAINERS FOR 130、显示用户数据库的存取权限GET AUTHORIZATIONS31、启动实例DB2START32、停止实例db2stop33、表或视图特权grant select,delete,insert,update on tables to user grant all on tables to user WITH GRANT OPTION34、程序包特权GRANT EXECUTEON PACKAGE PACKAGE-nameTO PUBLIC35、模式特权GRANT CREATEIN ON SCHEMA SCHEMA-name TO USER36、数据库特权grant connect,createtab,dbadm on database to user 37、索引特权grant control on index index-name to user38、信息帮助 (? XXXnnnnn )例:? SQL3008139、SQL 帮助(说明 SQL 语句的语法)help statement例如,help SELECT40、SQLSTATE 帮助(说明 SQL 的状态和类别代码) sqlstate 或 ? class-code41、更改与"管理服务器"相关的口令db2admin setid username password42、创建 SAMPLE 数据库db2sampldb2sampl F:(指定安装盘)43、使用操作系统命令! dir44、转换数据类型 (cast)SELECT EMPNO, CAST(RESUME AS VARCHAR(370))FROM EMP_RESUMEWHERE RESUME_FORMAT = 'ascii'45、UDF要运行 DB2 Java 存储过程或 UDF,还需要更新服务器上的 DB2 数据库管理程序配置,以包括在该机器上安装 JDK 的路径db2 update dbm cfg using JDK11_PATH d:\sqllib\java\jdkTERMINATEupdate dbm cfg using SPM_NAME sample46、检查 DB2 数据库管理程序配置db2 get dbm cfg47、检索具有特权的所有授权名SELECT DISTINCT GRANTEE, GRANTEETYPE, 'DATABASE' FROM SYSCAT.DBAUTHUNIONSELECT DISTINCT GRANTEE, GRANTEETYPE, 'TABLE ' FROM SYSCAT.TABAUTHUNIONSELECT DISTINCT GRANTEE, GRANTEETYPE, 'PACKAGE ' FROM SYSCAT.PACKAGEAUTHUNIONSELECT DISTINCT GRANTEE, GRANTEETYPE, 'INDEX ' FROM SYSCAT.INDEXAUTHUNIONSELECT DISTINCT GRANTEE, GRANTEETYPE, 'COLUMN ' FROM SYSCAT.COLAUTHUNIONSELECT DISTINCT GRANTEE, GRANTEETYPE, 'SCHEMA ' FROM SYSCAT.SCHEMAAUTHUNIONSELECT DISTINCT GRANTEE, GRANTEETYPE, 'SERVER ' FROM SYSCAT.PASSTHRUAUTHORDER BY GRANTEE, GRANTEETYPE, 3create 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','综合统计')50、事务的提交、回滚commit;rollback;51、查看db2的许可证信息Db2licm –l52、显示实例名称Db2ilist53、更新实例Db2iupdt instance_name54、DAS实例的配置信息Db2 get admin cfg55、其他实例的配置信息Db2 get dbm cfg或者db2 get database manager configuration56、数据库的配置信息Db2 get database configuration for database_name57、创建工具目录数据库db2 create tools catalog cc create new database toolsdb58、数据库备份CONNECT TO TAIS;QUIESCE DATABASE IMMEDIATE FORCE CONNECTIONS;CONNECT RESET;BACKUP DATABASE TAIS TO "D:\backup" WITH 2 BUFFERS BUFFER 1024 PARALLELISM 1 WITHOUT PROMPTING;CONNECT TO TAIS;UNQUIESCE DATABASE;59、数据库恢复db2 restore database tais from d:\backup taken at 20061017 without rolling forward60、切换实例(windows)set db2instance=tais61、创建全局临时表a、创建用户临时表空间db2 CREATE USER TEMPORARY TABLESPACE user_tempMANAGED BY SYSTEM USING('/home/inst##/usertemp')b、创建全局临时表DECLARE GLOBAL TEMPORARY TABLE table_name1LIKE table_name2 NOT LOGGEDfor example:db2 DECLARE GLOBAL TEMPORARY TABLE temployee LIKE employee NOT LOGGEDc、查看创建过的临时表select * from session.temployee需要取消事务的自动落实(update command options using c off) for example:db2>CONNECT TO sampledb2>LIST COMMAND OPTIONSdb2>UPDATE COMMAND OPTIONS USING C OFFdb2>LIST COMMAND OPTIONSdb2>DECLARE GLOBAL TEMPORARY TABLE tstaffLIKE staff NOT LOGGEDdb2>INSERT INTO session.tstaff SELECT * FROM staffdb2>SELECT * FROM session.staffdb2>COMMITdb2>SELECT * FROM staffdb2>CONNECT RESET62、创建模式名CREATE SCHEMA schema_name AUTHORIZATION auth_name63、断开当前的连接db2 DISCONNECT CURRENT64、创建视图CREATE VIEW view_name (column_names)AS fullselectWITH {LOCAL|CASCADED} CHECK OPTIONfor example:CREATE view NEW.V3 AS SELECT * FROM NEW.SALES AS SALES;CREATE view NEW.V4 AS SELECT * FROM NEW.SALES AS SALES WITH CASCADED CHECK OPTION;CREATE view NEW.V5 AS SELECT * FROM NEW.SALES AS SALES WITH LOCAL CHECK OPTION;65、创建序列CREATE SEQUENCE ORG_SEQSTART WITH 1INCREMENT BY 1NO MAXVALUENO CYCLECACHE 24--get sequencevalues nextval for seq166、得到当前时间values current timestamp67、创建索引type-2 indexes---对应用和并发进行保护,8版本以后使用a、Unique index —Ensures uniqueness of key column(s) datab、Bidirectional index(双向索引)—Allows scanning of indexes in eitherdirectionc、Clustered index(簇索引)— Places the rows of the tablein the samephysical order as the index keysd、多维索引---数据仓库中使用CREATE UNIQUE INDEX index_nameON table_name (column_name {ASC | DESC} [, column_name {ASC | DESC}…])INCLUDE column_namesCLUSTERPCTFREE integerMINPCTUSED integerALLOW REVERSE SCANSCREATE INDEX inON employee(empno ASC)PCTFREE 10MINPCTUSED 40Design Advisor in the CLP: db2advisfor example:db2advis -d database_name[{-w workload_name |-s "sql_statement" |-i filename}][-a userid[/password] ][-l disklimit][-t max_advise_time][-h][-p][-o out_file]db2advis -d sample-s "SELECT * FROM employee e WHERE firstnmeLIKE ’A%’"-a inst00/inst00-l 53-t 20exercises:a、create normal indexCONNECT TO SAMPLE;CREATE INDEX DB2ADMIN.IDX_STAFF_NAME ON NEW.STAFF ("NAME" ASC) PCTFREE 10 MINPCTUSED 10 COLLECT STATISTICS ;COMMENT ON Index DB2ADMIN.IDX_STAFF_NAME IS 'common index on column name ';CONNECT RESET;b、create unique indexCONNECT TO SAMPLE;CREATE UNIQUE INDEX DB2ADMIN.UIDX_STAFF_ID ON NEW.STAFF (ID ASC) PCTFREE 10 MINPCTUSED 10 COLLECT STATISTICS ;CONNECT RESET;c、create Bidirectional IndexCONNECT TO SAMPLE;CREATE INDEX DB2ADMIN.BIDX_STAFF_SALARY ONNEW.STAFF (SALARY ASC) PCTFREE 10 MINPCTUSED 10 ALLOW REVERSE SCANS COLLECT DETAILED STATISTICS ;CONNECT RESET;d、Create Clustered IndexCONNECT TO SAMPLE;CREATE INDEX DB2ADMIN.CIDX_STAFF_DEPT ON NEW.STAFF (DEPT ASC) CLUSTER PCTFREE 10 MINPCTUSED 10 COLLECT SAMPLED DETAILED STATISTICS ;CONNECT RESET;68、使用约束Using Constraints(主键的字段不可为空,唯一键的字段可以为空)a、Adding a Primary Key to an Existing TableALTER TABLE student ADD CONSTRAINT pk_id PRIMARY KEY(id)exercises:A、Use this command to create a new table called po_masterCREATE TABLE po_master (po_no INTEGER NOT NULL,po_date DATE NOT NULL,bill_no INTEGER NOT NULL,bill_date DATE NOT NULL,description VARCHAR (200),CONSTRAINT pk_po_master PRIMARY KEY (po_no),CONSTRAINT u_key_bill_no UNIQUE (bill_no))B、Use the following command to alter an existing table called po_masterALTER TABLE po_master ADD CONSTRAINT u_key_bill_no UNIQUE (bill_no)C、Using the CLP, create a table called po_master with a primary key on po_no using the following commandCREATE TABLE PO_DETAIL (po_no INTEGER NOT NULL,s_no INTEGER NOT NULL,item_code INTEGER NOT NULL,description VARCHAR (100),quantity INTEGER NOT NULL,rate INTEGER NOT NULL,PRIMARY KEY (po_no, s_no),CONSTRAINT fk_po_masterdetail FOREIGN KEY(po_no)REFERENCES administrator.po_master (po_no))D、There are four CREATE TABLE options for defining the delete rule:NO ACTION,RESTRICT :If RESTRICT or NO ACTION is selected, an error occurs and no records are deleted if you try to delete records from parent table.CASCADE: If CASCADE is selected, the delete operation is propagated to the dependent tables, that is, records in the po_master table as well as all the related records in the po_detailtable are automatically deleted.SET NULL: If SET NULL is selected, the delete operation in po_master table is allowed and the the related records in po_detail table are set to NULL.E、modify table---add restrict constraint(delete)CONNECT TO SAMPLE;ALTER TABLE DB2ADMIN.PO_DETAIL DROP FOREIGN KEY FK_PO_MASTERDETAIL ADD CONSTRAINT FK_PO_MASTERDETAIL FOREIGN KEY (PO_NO) REFERENCES DB2ADMIN.PO_MASTER (PO_NO) ON DELETE RESTRICT ON UPDATE NO ACTION ENFORCED ENABLE QUERY OPTIMIZATION ;CONNECT RESET;---add no action constraint(delete)CONNECT TO SAMPLE;ALTER TABLE DB2ADMIN.PO_DETAIL DROP FOREIGN KEY FK_PO_MASTERDETAIL ADD CONSTRAINT FK_PO_MASTERDETAIL FOREIGN KEY (PO_NO) REFERENCES DB2ADMIN.PO_MASTER (PO_NO) ON DELETE NO ACTION ON UPDATE NO ACTION ENFORCED ENABLE QUERY OPTIMIZATION ;CONNECT RESET;---add cascade constraint(delete)CONNECT TO SAMPLE;ALTER TABLE DB2ADMIN.PO_DETAIL DROP FOREIGN KEY FK_PO_MASTERDETAIL ADD CONSTRAINT FK_PO_MASTERDETAIL FOREIGN KEY (PO_NO) REFERENCESDB2ADMIN.PO_MASTER (PO_NO) ON DELETE CASCADE ON UPDATE NO ACTION ENFORCED ENABLE QUERY OPTIMIZATION ;CONNECT RESET;---add set null constraint(delete)CONNECT TO SAMPLE;ALTER TABLE DB2ADMIN.PO_DETAIL DROP FOREIGN KEY FK_PO_MASTERDETAIL ADD CONSTRAINT FK_PO_MASTERDETAIL FOREIGN KEY (PO_NO) REFERENCES DB2ADMIN.PO_MASTER (PO_NO) ON DELETE SET NULL ON UPDATE NO ACTION ENFORCED ENABLE QUERY OPTIMIZATION ;CONNECT RESET;---add restrict constraint(update)CONNECT TO SAMPLE;ALTER TABLE DB2ADMIN.PO_DETAIL DROP FOREIGN KEY FK_PO_MASTERDETAIL ADD CONSTRAINT FK_PO_MASTERDETAIL FOREIGN KEY (PO_NO) REFERENCES DB2ADMIN.PO_MASTER (PO_NO) ON DELETE RESTRICT ON UPDATE RESTRICT ENFORCED ENABLE QUERY OPTIMIZATION ;CONNECT RESET;---add no action constraint(update)CONNECT TOSAMPLE;ALTER TABLE DB2ADMIN.PO_DETAIL DROP FOREIGN KEY FK_PO_MASTERDETAIL ADD CONSTRAINT FK_PO_MASTERDETAIL FOREIGN KEY (PO_NO) REFERENCES DB2ADMIN.PO_MASTER (PO_NO) ON DELETE RESTRICT ON UPDATE NO ACTION ENFORCED ENABLE QUERY OPTIMIZATION ;CONNECT RESET;F、Using Check ConstraintsALTER TABLE po_master ADD CONSTRAINT chk_bill_date CHECK (bill_date <= po_date)69、导入导出数据DB2 supports the following data formats for extraction and insertion:◆ Delimited ASCII format (DEL)◆ Integrated exchange format (IXF)◆ Worksheet format (WSF)◆ Non-delimited ASCII (ASC)CONNECT TO SAMPLE;EXPORT TO "C:\无界定字符" OF DEL MESSAGES "C:\无界定字符.log" SELECT * FROM NEW.EMPLOYEE;CONNECT RESET;CONNECT TO SAMPLE;EXPORT TO "C:\界定字符" OF DEL MODIFIED BY COLDEL, MESSAGES "C:\界定字符.log" SELECT * FROM NEW.EMPLOYEE;CONNECT RESET;CONNECT TO SAMPLE;EXPORT TO "C:\工作表格式" OF WSF MODIFIED BY 1 MESSAGES "C:\工作表格式.log" SELECT * FROM NEW.EMPLOYEE;CONNECT RESET;CONNECT TO SAMPLE;EXPORT TO "C:\集成交换格式" OF IXF MESSAGES "C:\集成交换格式.log" SELECT * FROM NEW.EMPLOYEE;CONNECT RESET;CONNECT TO SAMPLE;IMPORT FROM "C:\界定字符" OF DEL METHOD P (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14) MESSAGES "C:\界定字符.log" INSERT INTO DB2ADMIN.EMPLOYEE_DUP (EMPNO, FIRSTNME, MIDINIT, LASTNAME, WORKDEPT, PHONENO, HIREDATE, JOB, EDLEVEL, SEX, BIRTHDATE, SALARY, BONUS, COMM);CONNECT RESET;CONNECT TO SAMPLE;IMPORT FROM "C:\工作表格式" OF WSF MESSAGES "C:\工作表格式.log" INSERT INTO DB2ADMIN.EMPLOYEE_DUP;CONNECT RESET;CONNECT TO SAMPLE;IMPORT FROM "C:\集成交换格式" OF IXF MESSAGES "C:\集成交换格式.log" INSERT INTO DB2ADMIN.EMPLOYEE_DUP;CONNECT RESET;70、装载数据db2 "CONNECT TO sample"db2 "CREATE TABLE exc_emp LIKE employee"db2 "ALTER TABLE exc_emp ADD COLUMN time TIMESTAMP"db2 "ALTER TABLE exc_emp ADD COLUMN message CLOB(32K)"db2 "CREATE TABLE employee_dup LIKE employee"db2 "ALTER TABLE employee_dup ADD CONSTRAINTchk_cnst CHECK(EDLEVEL > 12)"CONNECT TO SAMPLE;LOAD FROM "C:\界定字符" OF DEL METHOD P (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14) MESSAGES "C:\界定字符.log" INSERT INTO DB2ADMIN.EMPLOYEE_DUP (EMPNO, FIRSTNME, MIDINIT, LASTNAME, WORKDEPT, PHONENO, HIREDATE, JOB, EDLEVEL, SEX, BIRTHDATE, SALARY, BONUS, COMM) COPY NO INDEXING MODE AUTOSELECT;CONNECT RESET;---check constraintdb2 SET INTEGRITY FOR employee_dup IMMEDIATE CHECKED FOR EXCEPTION IN employee_dup USE exc_emp71、生成DDL语句---single schemadb2look -d SAMPLE -z NEW -u DB2ADMIN -e -l -x -m -r ;---full databasedb2look -d SAMPLE -a -e -l -x -m -r -f ;72、索和并发控制DB2 provides different levels of protection to isolate data:◆ Uncommitted read◆ Cursor stability◆ Read stability◆ Repeatable read---default isolation levelCursor stabilityexercise(using ur isolation):1.1 Open two Command Line Processor windows. We will refer to these windowsas W1 and W2. Make sure they connect to the correct instance before moving to the nextstep.1.2 Set the AUTOCOMMIT feature OFF in both W1 and W2 by executing this command:db2 => update command options using c off1.3 Change isolation level of W1 to uncommitted read.db2 => CHANGE ISOLATION TO URdb2 => CONNECT TO sample1.4 Now go to W2 where the default isolation is cursor stability. Run these commands:db2 => CONNECT TO sampledb2 => UPDATE staff SET salary = salary + 101.5 Go back to W1 and run the following statement to view dirty records from the staff table.db2 => SELECT * FROM staffYou will see updated, but not committed data in W2. This is known as a dirty read.1.6 Again switch to W2 and roll back the transaction.db2 => ROLLBACK1.7 Now, you can get actual data in W1:db2 => SELECT * FROM staff1.8 Close both windows W1 and W2.exercise(Locking a Database)The syntax for the CONNECT command is shown here:CONNECT TO database_name [IN EXCLUSIVE MODE]Execute the following command:db2 CONNECT TO sample IN EXCLUSIVE MODEUSER your_login USING your_passwordNow, try to connect to sample database as any user other than your_login. The followingmessage is returned:db2 connect to sample user test using testSQL1035N The database is currently in use. SQLSTATE=5701973、出错处理实例参数:diaglevel=3日志文件:D:\IBM\SQLLIB\DB274、View Registry VariablesUse the db2set command to view registry variable values:db2set -i for instance-level parametersdb2set -g for global-level parametersdb2set -I for all the defined profilesdb2set -all for all the registry variables with valuesdb2set -lr for all available parametersTo set a parameter for the current instance:Syntax: db2set parameter=valueExample: db2set DB2COMM=tcpip,npipeTo set a parameter’s value for a specific instance:Syntax: db2set parameter=value -i instance_nameExample: db2set DB2COMM=tcpip,npipe -i altinstTo set a parameter at the global level:Syntax: db2set parameter=value -gExample: db2set DB2COMM=tcpip,npipe -g75、Cataloging the ServerSyntax for cataloging a server:CATALOG TCPIP NODE node_nameREMOTE {hostname | ip_address}SERVER {svcename | port_number}Example:CATALOG TCPIP NODE db2serv REMOTE 9.186.128.141 SERVER 370076、cataloging the databaseSyntax for cataloging a database:CATALOG DATABASE db_name AS db_aliasAT NODE node_nameExample:CATALOG DATABASE sample AS srv_sampAT NODE db2server二、目录视图说明说明目录视图检查约束 SYSCAT.CHECKS列 SYSCAT.COLUMNS检查约束引用的列 SYSCAT.COLCHECKS关键字中使用的列 SYSCAT.KEYCOLUSE数据类型 SYSCAT.DATATYPES函数参数或函数结果 SYSCAT.FUNCPARMS参考约束 SYSCAT.REFERENCES模式 SYSCAT.SCHEMATA表约束 SYSCAT.TABCONST表 SYSCAT.TABLES触发器 SYSCAT.TRIGGERS用户定义函数 SYSCAT.FUNCTIONS视图 SYSCAT.VIEWS三、字符串类型二进制大对象 (BLOB) 字符串。

DB2数据库的常用操作指令

DB2数据库的常用操作指令

DB2数据库的常用操作指令DB2是一种关系型数据库管理系统,其常用操作指令可以帮助用户在数据库中执行各种操作。

以下是DB2数据库的一些常用操作指令。

1.连接数据库:CONNECT TO database_name [USER username USING password]2.断开数据库连接:CONNECTRESET3.创建表:CREATE TABLE table_name (column1 datatype, column2 datatype, ...)4.删除表:DROP TABLE table_name5.修改表结构:ALTER TABLE table_name ALTER COLUMN column_name SET DATA TYPE datatype6.插入数据:INSERT INTO table_name (column1, column2, ...) VALUES (value1, value2, ...)7.更新数据:UPDATE table_name SET column1 = value1, column2 = value2 WHERE condition8.删除数据:DELETE FROM table_name WHERE condition9.查询数据:SELECT column1, column2, ... FROM table_name WHERE condition 10.创建索引:CREATE INDEX index_name ON table_name (column1, column2, ...)11.删除索引:DROP INDEX index_name12.创建视图:CREATE VIEW view_name AS SELECT column1, column2, ... FROM table_name WHERE condition13.修改视图:ALTER VIEW view_name AS SELECT column1, column2, ... FROM table_name WHERE condition14.删除视图:DROP VIEW view_name15.创建存储过程:CREATE PROCEDURE procedure_name (parameter1 datatype, parameter2 datatype, ...)LANGUAGESQLBEGIN--存储过程代码END16.删除存储过程:DROP PROCEDURE procedure_name17.创建触发器:CREATE TRIGGER trigger_name BEFORE/AFTERINSERT/UPDATE/DELETE ON table_nameREFERENCING OLD ROW AS old NEW ROW AS newFOREACHROW--触发器代码18.删除触发器:DROP TRIGGER trigger_name19.提交事务:COMMIT20.回滚事务:ROLLBACK21.创建数据库:CREATE DATABASE database_name22.删除数据库:DROP DATABASE database_name以上是DB2数据库的一些常用操作指令,可以帮助用户在数据库中执行各种操作。

DB2常用命令

DB2常用命令
db2 list application show detail | grep irge01
db2>> force application(20570)
查看表是否锁:load query table table_name
清光表数据:import from /dev/null of del replace into table_name
查找hxusr模式名下的所有表:db2 "list tables for schema hxusr ";
select中创建序号:select ROW_NUMBER()OVER(【分组】partition by brhid 【排序】order by acct_no) as a,acct_no,br_name from b_sbrhm
select中判断字段输出值:select (case when mat_dt=999999999 then 2958464 else mat_dt end) as mat_dt from b_mtermacctinfo
测试decimal处理定长:
db2 "values char(decimal('6.000',9,4))" :00006.0000
连接数据库:connect to db_name(数据库) user hxusr(用户) using hxusr1(口令)
A中的表数据想要根据B表的数据相应进行update:
update A set bal=(select txnamt from B where actno=A.actno and cnlno=lno) where A.actno||lno in (select Actno||cnlno from B )

DB2操作常用命令

DB2操作常用命令

1、数据操作语言(DML:select,delete,insert,update)<1>查询数据库目录:db2 list db directory<2>查询数据库中表db2 list tables 当前用户db2 list tables for all 所有表db2 list tables for schema schemaname 指定模式的表<3>显示表结构db2 describe table tablename<4>插入数据db2 insert into tablename(字段名,字段名...) values (与字段名一一对应的值)db2 insert into tablename1(字段1,字段2,字段3...)select 字段1,字段2,字段3...from tablename2 + 查询条件<5>更改表或视图数据db2 update tablename/viewname set 字段名1='',字段2='',...+查询条件<6>删除数据db2 delete from tablename where + 条件<7>导入数据db2 "import from E:\name.txt of del insert into tableName" db2 "import from E:\name.ixf of ixf commitcount 5000 insert /create/replace into tableName"db2 "load client from D:\xx.txt of del insert/replace into tabName"(不需要写日志,但插入前表必须存在;不能create table)db2 "load client from D:\xx.txt of del restart/terminate into tabName" 当导入数据出现问题被强行中断时,此表会被加锁,通过此命令可以解锁<8>导出数据db2 "export to E:\name.txt of del select * from tableName" db2 "export to E:\name.txt of del MODIFIED BY NOCHARDEL select * from tableName"(导出不带分号的数据)导出表结构和数据db2 "export to E:\name.ixf of ixf MODIFIED BY NOCHARDEL select * from tableName"db2 "export to E:\name.ixf of ixf MODIFIED BY NOCHARDEL select * from tableName fetch first (取数+UNM) rows only"(取固定条数) 导出表结构db2look -d dbName -e -t tableName -o D:\xxx.sql(path) -i userName -w passworddb2look -d dbName -z tabSchema -e -c -i userName -w password -o + 路径名导出存储过程结构db2 "export to xxx.sql of del select text fromsyscat.procedures where procname='大写存储过程名'"<9>查询表状态db2 load query table + tableName<10>查询当前表数据量(数据入库时)db2 select count(1) from tab with ur<11>修改当前表名、模式名db2 rename table tab1 to tab22、数据定义语言(DDL:create,alter)<1>创建或删除实例db2icrt instance_name/db2idrop -f instance_namelinux:db2icrt -u user_id instance_name<2>创建视图、表、模式db2 create view/table/schema创建指定用户的模式db2 create schema schName AUTHORIZATION userNamedb2 create schema AUTHORIZATION userName(没有指定模式名时,模式名隐含为用户名userName)定义含有缺省值的表db2 create table tableName(column1 数据类型,column2 数据类型default '缺省值')基于已存在的表db2 create table clone_tablename like tablenamedb2 create table clone_tablename as (select * from tablename) definition only创建物化查询表(MQT)create table new_table_name as (select * from table_name) data initially deferred refresh deferred;refresh table new_table_name;注意:物化表类似一个查询,没有真正形成表,类型显示为Query。

DB2命令——精选推荐

DB2命令——精选推荐

DB2命令DB2命令总汇DB2常⽤命令汇总之⼀db2 -tvf my.sqldb2level 显⽰db2的版本号显⽰SQL出错信息db2 "? sql6031"db2mtrk管理DAS产⽣:root运⾏-dascrt -u dasuser1删除:root运⾏-dasdrop启动:dasusr1运⾏-db2admin start停⽌:dasusr1运⾏-db2admin stopdb2_killipcleandb2start dbpartitionnum 9 restartAIX启动控制中⼼:db2ccDB2⽤户管理:db2 use os to manage users.You can use following steps to add a db2 user:1,add a user on os.2,grant rights to user.GRANT CREATETAB,CONNECT ON DATABASE TO USER FUJIE;grant select, update, delete on table employee to user john with grant option⼀,实例产⽣db2icrt -a AuthType(SERVER,CLIENT,SERVER_ENCRYPT) -p PORT_NAME表空间PREFETCHSIZE的设置,EXTENTSIZE的关系,缓冲池的监控,页清除程序的多少。

临时表空间页⾯⼤⼩与其他表空间页⾯⼤⼩的设置,临时表空间与缓冲池的设置。

example:db2icrt db2 -s ese -p d:\db2 -u Administrator注意:在UNIX 上产⽣实例时需要产⽣⼀个和实例名称相同的⽤户名,和fencedid ⽤户。

如:db2icrt -s ese -u db2fenc2 db2inst2 将在db2inst2⽤户中产⽣实例db2inst2.缺省创建32位实例,创建64位实例:db2icrt -s ese -w 64 -u db2fenc2 db2inst2删除db2idrop instance-name启动db2start停⽌db2stop force连接db2 attach to testdb2db2 detach列出实例db2ilist设置当前实例set db2instance=得到当前实例db2 get instance设置实例⾃动重启动UNIXdb2iauto -ondb2iauto -off获取实例的配置参数db2 get dbm cfg修改配置参数例如:db2 update dbm cfg using authentication server_encryptdb2stop and db2start⼆,声明注册表和环境变量db2set 注意:设置完成后需要退出⽤户,再注册进⼊才能⽣效。

db2常用命令

db2常用命令

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 initialize tape on \\.\tape0)
(db2 rewind tape on \\.\tape0)
db2 backup db o_yd to \\.\tape0
10.恢复数据库
db2 restore db o_yd from d: to d:
list tables
19.列出所有的系统表
list tables for system
20.查看表结构
db2 describe select * from user.tables
db2 force application ID1,ID2,,,Idn MODE ASYNC
(db2 list application for db o_yd show detail)
9.备份数据库
db2 force application all
db2 backup db o_yd to d:
db2 import to c:\dftz.ixf of ixf commitcount 5000 insert_update into dftz
db2 import to c:\dftz.ixf of ixf commitcount 5000 replace into dftz
db2 import to c:\dftz.ixf of ixf commitcount 5000 create into dftz (仅IXF)

db2数据库 sql常用命令

db2数据库 sql常用命令

DB2数据库 SQL常用命令一、连接数据库1. 从命令行连接数据库- 语法: db2 connect to <database_name> user <username> using <password>- 示例: db2 connect to sample user db2inst1 using passw0rd2. 从命令行断开数据库连接- 语法: db2 connect reset- 示例: db2 connect reset3. 显示当前连接的数据库- 语法: db2 list database directory- 示例: db2 list database directory二、管理数据库对象4. 创建数据库- 语法: db2 create database <database_name>- 示例: db2 create database sample5. 删除数据库- 语法: db2 drop database <database_name>- 示例: db2 drop database sample6. 创建表- 语法: db2 create table <table_name> (<column1_name> <data_type>, <column2_name> <data_type>, ...)- 示例: db2 create table employee (id int, name varchar(50), age int)7. 删除表- 语法: db2 drop table <table_name>- 示例: db2 drop table employee8. 插入数据- 语法: db2 insert into <table_name> values (<value1>,<value2>, ...)- 示例: db2 insert into employee values (1, 'John', 25)9. 删除数据- 语法: db2 delete from <table_name> where <condition> - 示例: db2 delete from employee where id = 110. 更新数据- 语法: db2 update <table_name> set <column_name> =<new_value> where <condition>- 示例: db2 update employee set age = 30 where id = 111. 查询数据- 语法: db2 select <column1_name>, <column2_name>, ... from <table_name> where <condition>- 示例: db2 select * from employee三、管理数据库事务12. 启动事务- 语法: db2 autmit off- 示例: db2 autmit off13. 提交事务- 语法: db2mit- 示例: db2mit14. 回滚事务- 语法: db2 rollback- 示例: db2 rollback四、管理数据库权限15. 创建用户- 语法: db2 create user <username> password <password> - 示例: db2 create user testuser password testpass16. 授权- 语法: db2 grant <privilege> on <object> to <user>- 示例: db2 grant select, insert, update on employee to testuser17. 撤销授权- 语法: db2 revoke <privilege> on <object> from <user> - 示例: db2 revoke select, insert, update on employee from testuser五、管理数据库性能18. 优化SQL查询- 语法: db2expln -d <database_name> -t <sql_statement> - 示例: db2expln -d sample -t "select * from employee"19. 查看数据库锁- 语法: db2 list applications show det本人l- 示例: db2 list applications show det本人l20. 查看数据库表空间使用情况- 语法: db2pd -d <database_name> -tablespaces- 示例: db2pd -d sample -tablespaces六、其他常用命令21. 导出数据- 语法: db2 export to <file_name> of del select * from<table_name>- 示例: db2 export to employee.csv of del select * from employee22. 导入数据- 语法: db2 import from <file_name> of del insert into<table_name>- 示例: db2 import from employee.csv of del insert into employee23. 查看数据库配置参数- 语法: db2 get db cfg for <database_name>- 示例: db2 get db cfg for sample结语以上就是DB2数据库SQL常用命令的介绍,通过掌握这些命令,可以更方便地管理和使用DB2数据库。

DB2常用命令小结

DB2常用命令小结

DB2常⽤命令⼩结1、打开命令⾏窗⼝ #db2cmd2、打开控制中⼼ # db2cmd db2cc3、打开命令编辑器 db2cmd db2ce=====操作数据库命令=====4、启动数据库实例 #db2start5、停⽌数据库实例 #db2stop 如果你不能停⽌数据库由于激活的连接,在运⾏db2stop前执⾏db2 force application all就可以了 /db2stop force 6、创建数据库 #db2 create db [dbname]7、连接到数据库 #db2 connect to [dbname] user [username] using [password]8、断开数据库连接 #db2 connect reset9、列出所有数据库 #db2 list db directory10、列出所有激活的数据库 #db2 list active databases11、列出所有数据库配置 #db2 get db cfg12、删除数据库 #db2 drop database [dbname](执⾏此操作要⼩⼼)如果不能删除,断开所有数据库连接或者重启db2=========操作数据表命令==========13、列出所有⽤户表 #db2 list tables14、列出所有系统表 #db2 list tables for system15、列出所有表 #db2 list tables for all16、列出系统表 #db2 list tables for system17、列出⽤户表 #db2 list tables for user18、列出特定⽤户表 #db2 list tables for schema [user]19、创建⼀个与数据库中某个表(t2)结构相同的新表(t1) #db2 create table t1 like t220、将⼀个表t1的数据导⼊到另⼀个表t2#db2 "insert into t1 select * from t2"21、查询表 #db2 "select * from table name where ..."22、显⽰表结构 #db2 describe table tablename23、修改列 #db2 alter table [tablename] alter column [columname] set data type varchar(24)======脚本⽂件操作命令=======24、执⾏脚本⽂件 #db2 -tvf scripts.sql25、帮助命令* 查看命令帮助 #db2 ? db2start* 查看错误码信息#db2 ? 22001* memo: 详细命令请使⽤"db2 ? <command>"进⾏查看。

DB2 常用命令速查

DB2 常用命令速查
db2level - 显示 DB2 服务级别
db2licm - 许可证管理工具
db2listvolumes - 显示所有磁盘卷的 GUID
db2logsforrfwd - 列示前滚恢复所需的日志
db2look - DB2 统计信息和 DDL 抽取工具
db2ls - 列出已安装的 DB2 产品和功能部件
db2move - 数据库移动工具
db2mqlsn - MQ 侦听器
db2mscs - 设置 Windows 故障转移实用程序
db2mtrk - 内存跟踪程序
db2nchg - 更改数据库分区服务器配置
db2ncrt - 将数据库分区服务器添加至实例
db2ndrop - 从实例中删除数据库分区服务器
db2swtch - 切换缺省 DB2 副本
db2sync - 启动 DB2 同步器
db2systray - 启动 DB2 系统任务栏
db2tapemgr - 管理磁带上的日志文件
db2tbst - 获取表空间状态
db2trc - 跟踪
db2uiddl - 准备转换为 V5 语义的唯一索引转换
dasauto - 自动启动 DB2 管理服务器
dascrt - 创建 DB2 管理服务器
dasdrop - 除去 DB2 管理服务器
dasmigr - 迁移 DB2 管理服务器
dasupdt - 更新 DB2 管理服务器
db2_deinstall - 卸载 DB2 产品或功能部件
db2_install - 安装 DB2 产品
db2exfmt - 说明表格式
db2exmig - 迁移说明表命令

db2常用命令

db2常用命令

DB2常用命令连接数据库: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 GROUPIBMDEFAULTGROUP 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):db2start2. 停止实例(db2inst1):db2stop3. 列出所有实例(db2inst1)db2ilist5.列出当前实例:db2 get instance4. 察看示例配置文件:db2 get dbm cfg|more5. 更新数据库管理器参数信息:db2 update dbm cfg using para_name para_value 6. 创建数据库:db2 create db test7. 察看数据库配置参数信息db2 get db cfg for test|more8. 更新数据库参数配置信息db2 update db cfg for test using para_name para_value 10.删除数据库:db2 drop db test11.连接数据库db2 connect to test12.列出所有表空间的详细信息。

db2数据库常用命令

db2数据库常用命令

db2常用命令0.进入db2命令环境db2cmd1.启动db2db2start;2.关闭db2db2stop;db2stop force;3.创建数据库db2 create db ;db2 create db using codeset GBK territory CN;db2 Create database using codeset IBM-eucCN territory CN;这样可以支持中文。

4.删除数据库(执行此操作要小心)db2 drop db如果不能删除,断开所有数据库连接或者重启db2。

5.断开数据库连接db2 force application all6.连接数据库db2 connect to user using7.断开数据库连接断开当前数据库连接:db2 connect reset或者:db2 disconnect current断开所有数据库的连接:db2 disconnect all8.备份数据库db2 backup db备注:执行以上命令之前需要断开数据库连接9.恢复数据库db2 restore db10.导出数据文件db2move export [-sn <模式名称,一般为db2admin>] [-tn <表名,多个之间用逗号分隔>]; 更多时候用下面这种方式:db2 export to test.ixf of ixf select * from11.导入数据文件db2move importdb2 import from text.ixf of ixf create into ;(表不存在)db2 import from text.ixf of ixf insert into ;(表已经存在)12.建立映像:db2 catalog tcpip node nodename remote 10.0.2.3 server 50000db2 catalog db dbname at node nodename13.撤销映像:db2 uncatalog db dbname14.列出数据库中所有db:db2 list db directory15.获取建表脚本:db2look -d dbname -e -t tablename -a -x -i userId -w password -o filename.sql-d: 数据库名:这必须指定-e: 抽取复制数据库所需要的 DDL 文件-u: 创建程序标识:若 -u 和 -a 都未指定,则将使用 $USER-z: 模式名:如果同时指定了 -z 和 -a,则将忽略 -z-t: 生成指定表的统计信息-h: 更详细的帮助消息-o: 将输出重定向到给定的文件名-a: 为所有创建程序生成统计信息-m: 在模拟方式下运行 db2look 实用程序-c: 不要生成模拟的 COMMIT 语句-r: 不要生成模拟的 RUNSTATS 语句-l: 生成数据库布局:数据库分区组、缓冲池和表空间。

DB2系统命令

DB2系统命令

Memory for database: testdb
Backup/Restore/Util Heap has max size of 249200640 bytes
Package Cache has max size of 2089811968 bytes
18、db2expln - SQL and XQuery Explain
生成sql文执行计划。-u后面跟用户名和密码,-t输出到console
db2expln -d testdb -u shen shen -q “select * from tblAreaCode” -t
db2expln -d testdb -u shen shen -q “select * from tblAreaCode” -o my.exp
1、dasauto
在$DB2DIR/das/adm目录下,设置DAS是否自启动状态。dasauto [-h|-?] -on|-off。
如果在inittab文件中不禁止db2fmcd进程,上面设置无效,因为dbfmcd进程会启动db2fmd,db2fmd在一定周期内启动DAS。
2、dascrt
16、db2drdat - DRDA trace
跟踪DRDA通信。
db2drdat on #首先打开trace,也可以指定trace buffer大小
db2drdat off -t=abc.dmp[如果不指定缺省是db2drdat.dmp] #关闭trace,将trace buffer内容写入abc.dmp
db2look -d testdb -u shen -m abc -e -o shen.sql
4)生成tbtest表格的ddl

DB2常用命令

DB2常用命令

DB2常⽤命令 在开发过程中总结的⼀些DB2的常⽤命令,也是⾃⼰需要⽤的时候在⽹上查的,在此做个汇总。

⼀、DB2导⼊/导出表数据语句1.1 del与ixf区别 del格式是⼀个⽂本⽂件,⽂件按⾏来存储,含有回车的⽂本内容在del⽂件中会另起⼀⾏,del⽂件可视;ixf格式保存的是结构和数据,是⼀个⼆进制⽂件,ixf⽂件不可视。

1.2 正常的导⼊/出数据 db2 "export to 路径/⽂件名.ixf of ixf select * from tablename"; db2 "export to 路径/⽂件名.del of del select * from tablename" db2 "import from 路径/⽂件名.del或者⽂件名.txt of del insert into tablename"; db2 "import from 路径/⽂件名.ixf或者⽂件名.ixf of ixf insert into tablename";1.3 指定编码导⼊/导出数据 1383是gb2312 db2 "export to data819.del of del modified by codepage=1208 select * from tab1" 1208是utf-8 db2 "export to data1386.del of del modified by codepage=1383 select * from tab1"1.4 指定分隔符导⼊/ coldel + 分隔符 db2 “import from 路径/⽂件名 of del modified by coldel分割符号 insert into 表名”1.5 导出/导⼊数据⽣成⽇志⽂件 db2 “import from 路径/⽂件名.ixf of ixf commitcount 5000(提交总数) messages ⽇志路径/⽇志⽂件名.log insert into 表名”;1.6 db2move:导出表的数据 与export命令功能相似。

DB2常用命令

DB2常用命令

DB2常用的命令1.启动数据库db2start2.停止数据库db2stop3.连接数据库db2 connect to oyd user db2 using pwd(注:oyd为数据库名)4.读数据库管理程序配置db2 get dbm cfg5.写数据库管理程序配置db2 update dbm cfg using 参数名参数值6.读数据库的配置db2 connect to o_yd user db2 using pwddb2 get db cfg for o_yd7.写数据库的配置db2 connect to o_yd user db2 using pwddb2 update db cfg for o_yd using 参数名参数值8.关闭所有应用连接db2 force application alldb2 force application ID1,ID2,,,Idn MODE ASYNC(db2 list application for db o_yd show detail)9.备份数据库db2 force application alldb2 backup db o_yd to d:(db2 initialize tape on \\.\tape0)(db2 rewind tape on \\.\tape0)db2 backup db o_yd to \\.\tape010.恢复数据库db2 restore db o_yd from d: to d:db2 restore db o_yd from \\.\tape0 to d:11.绑定存储过程db2 connect to o_yd user db2 using pwddb2 bind c:\dfplus.bnd拷贝存储过程到服务器上的C:\sqllib\function目录中12.整理表db2 connect to o_yd user db2 using pwddb2 reorg table ydddb2 runstats on table ydd with distribution and indexes all 13.导出表数据db2 export to c:\dftz.txt of del select * from dftzdb2 export to c:\dftz.ixf of ixf select * from dftz14.导入表数据import from c:\123.txt of del insert into ylbx.czyxxdb2 import to c:\dftz.txt of del commitcount 5000 messages c:\dftz.msg insert into dftzdb2 import to c:\dftz.ixf of ixf commitcount 5000 messages c:\dftz.msg insert into dftzdb2 import to c:\dftz.ixf of ixf commitcount 5000 insert into dftzdb2 import to c:\dftz.ixf of ixf commitcount 5000 insert_update into dftzdb2 import to c:\dftz.ixf of ixf commitcount 5000 replace into dftzdb2 import to c:\dftz.ixf of ixf commitcount 5000 create into dftz (仅IXF)db2 import to c:\dftz.ixf of ixf commitcount 5000 replace_create into dftz (仅IXF) 15.执行一个批处理文件db2 –tf 批处理文件名(文件中每一条命令用;结束)16.自动生成批处理文件建文本文件:temp.sqlselect 'runstats on table DB2.' || tabname || ' with distribution and detailed indexes all;' from syscat.tables where tabschema='DB2' and type='T';db2 –tf temp.sql>runstats.sql17.自动生成建表(视图)语句在服务器上:C:\sqllib\misc目录中db2 connect to o_yd user db2 using pwddb2look –d o_yd –u db2 –e –p –c c:\o_yd.txt18.其他命令grant dbadm on database to user bb19select * from czyxx fetch first 1 rows only20db2look –d ylbx –u db2admin –w –asd –a –e –o a.txt21. 显示当前用户所有表list tables22.列出所有的系统表list tables for system23.查看表结构db2 describe select * from user.tablesDB2常用的SQL语句1、组合语句执行BEGIN ATOMIC表达式1 分号空格/回车表达式2 分号空格/回车END2、应该限制访问权限的表(应该撤销这些表PUBLIC SELECT访问权)SYSCAT.DBAUTHSYSCAT.TABAUTHSYSCAT.PACKAGEAUTHSYSCAT.INDEXAUTHSYSCAT.COLAUTHSYSCAT.PASSTHRUAUTHSYSCAT.SCHEMAAUTH比较有用的目录表SYSCAT.COLUMNS:包含每一行对应于表或视图中定义的列SYSCAT.INDEXCOLUSE:包含每一行包含的所有列SYSCAT.INDEXES:包含每一行对应于表或视图中定义的每个索引SYSCAT.TABLES:所创建每个表,视图,别名对应其中一行SYSCAT.VIEWS:所创建每个视图对应其中一行或几行通过索引保持数据唯一性:CREATE UNIQUE INDEX INDEXNAME ON TABLE (COLUMN)消除重复行:SELECT DISTINCT COLUMN FROM TABLE3、DB2关于时间的一些函数得到当前时间的年份、月份、天、小时等等:YEAR (current timestamp)MONTH (current timestamp)DAY (current timestamp)HOUR (current timestamp)MINUTE (current timestamp)SECOND (current timestamp)MICROSECOND (current timestamp)分别得到当时的日期和时间DATE (current timestamp)TIME (current timestamp)关于时间的一些计算:current date + 1 YEARcurrent date + 3 YEARS + 2 MONTHS + 15 DAYScurrent time + 5 HOURS - 3 MINUTES + 10 SECONDS计算两个日期之间有多少天:days (current date) - days (date(’1999-10-22′))得到去除毫秒的当前时间:CURRENT TIMESTAMP - MICROSECOND (current timestamp) MICROSECONDS将时间转换成字符串:char(current date)char(current time)char(current date + 12 hours)将字符串转换成时间:TIMESTAMP (’2002-10-20-12.00.00.000000′)TIMESTAMP (’2002-10-20 12:00:00′)DATE (’2002-10-20′)DATE (’10/20/2002′)TIME (’12:00:00′)TIME (’12.00.00′)注意:在DB2的命令编辑器中可以输入SQL语句和DB2中的内部命令。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

DB2 常用命令,对于使用db2的朋友可以参考下。

1、打开命令行窗口#db2cmd2、打开控制中心# db2cmd db2cc3、打开命令编辑器db2cmd db2ce=====操作数据库命令=====4、启动数据库实例#db2start5、停止数据库实例#db2stop如果你不能停止数据库由于激活的连接,在运行db2stop前执行db2 force application all就可以了/db2stop force6、创建数据库#db2 create db [dbname]7、连接到数据库#db2 connect to [dbname] user [username] using [password]8、断开数据库连接#db2 connect reset9、列出所有数据库#db2 list db directory10、列出所有激活的数据库#db2 list active databases11、列出所有数据库配置#db2 get db cfg12、删除数据库#db2 drop database [dbname](执行此操作要小心)如果不能删除,断开所有数据库连接或者重启db2=========操作数据表命令==========13、列出所有用户表#db2 list tables14、列出所有系统表#db2 list tables for system15、列出所有表#db2 list tables for all16、列出系统表#db2 list tables for system17、列出用户表#db2 list tables for user18、列出特定用户表#db2 list tables for schema [user]19、创建一个与数据库中某个表(t2)结构相同的新表(t1)#db2 create table t1 like t220、将一个表t1的数据导入到另一个表t2#db2 "insert into t1 select * from t2"21、查询表#db2 "select * from table name where ..."22、显示表结构#db2 describe table tablename23、修改列#db2 alter table [tablename] alter column [columname] set data type varchar(24) ======脚本文件操作命令=======24、执行脚本文件#db2 -tvf scripts.sql25、帮助命令* 查看命令帮助#db2 ? db2start* 查看错误码信息#db2 ? 22001* memo: 详细命令请使用"db2 ? <command>"进行查看。

=========================26、备份数据库#db2 backup db <db name>备注:执行以上命令之前需要断开数据库连接27、在线备份数据库#db2 -v "BACKUP DATABASE <database name> ONLINE TO <path> WITH 2 BUFFERS BUFFER 1024 INCLUDE LOGS WITHOUT PROMPTING"28、恢复数据库#db2 restore db <source db name>29、在线恢复数据库#db2 "RESTORE DB <database name> TO <db path> LOGTARGET <logpath> WI THOUT PROMPTING"#db2 "ROLLFORWARD DB <database name> TO END OF LOGS AND STOP" ...30、导出数据文件#db2move <db name> export[-sn <模式名称,一般为db2admin>][-tn <表名,多个之间用逗号分隔>]31、导入数据文件#db2move <db name> import32、获取db2数据库管理配置环境信息#db2 get dbm cfg33、.获取db2某个数据库数据库管理配置环境信息#db2 get db cfg for <db name>或者:连接至某个数据库以后执行db2 get db cfg34、更改db2日志空间的大小备注:以下命令为了防止db2数据库过份使用硬盘空间而设,仅用于开发者自己机器上的d b2,如果是服务器,则参数需要修改。

#db2 UPDATE DB CFG FOR <db name> USING logretain OFF logprimary 3 logse cond 2 logfilsiz 25600;如果页大小是4KB,则以上命令创建3个100M的日志文件,占用300MB硬盘空间。

256 00*4KB=102400KB。

35、创建临时表空间#DB2 CREATE USER TEMPORARY TABLESPACE STMASPACE PAGESIZE 32 K MANAGED BY DATABASE USING (FILE 'D:\DB2_TAB\STMASPACE.F1' 10000) EXTENTSIZE 25636、获取数据库管理器的快照数据#db2 –v get snapshot for dbm37、显示进行程号#db2 list applications show detail===================================================一、加载数据:1、以默认分隔符加载,默认为“,”号db2 "import from btpoper.txt of del insert into btpoper"2、以指定分隔符“|”加载db2 "import from btpoper.txt of del modified by coldel| insert into btpoper"二、卸载数据:1、卸载一个表中全部数据db2 "export to btpoper.txt of del select * from btpoper"db2 "export to btpoper.txt of del modified by coldel| select * from btpoper"2、带条件卸载一个表中数据db2 "export to btpoper.txt of del select * from btpoper where brhid='907020000'" db2 "export to cmmcode.txt of del select * from cmmcode where codtp='01'"db2 "export to cmmcode.txt of del modified by coldel| select * from cmmcode where codtp='01'"三、查询数据结构及数据:db2 "select * from btpoper"db2 "select * from btpoper where brhid='907020000' and oprid='0001'"db2 "select oprid,oprnm,brhid,passwd from btpoper"四、删除表中数据:db2 "delete from btpoper"db2 "delete from btpoper where brhid='907020000' or brhid='907010000'"五、修改表中数据:db2 "update svmmst set prtlines=0 where brhid='907010000' and jobtp='02'"db2 "update svmmst set prtlines=0 where jobtp='02' or jobtp='03'"六、联接数据库db2 connect to btpdbs七、清除数据库联接db2 connect reset 断开数据库连接db2 terminate 断开数据库连接db2 force applications all 断开所有数据库连接八、备份数据库1、db2 backup db btpdbs2、db2move btpdbs exportdb2look -d btpdbs -e -x [-a] -o crttbl.sql九、恢复数据库1、db2 restore db btpdbs without rolling forward2、db2 -tvf crtdb.sqlcrtdb.sql文件内容:create db btpdbs on /db2catalogdb2 -stvf crttbl.sqldb2move btpdbs import十、DB2帮助命令:db2 ?db2 ? restroedb2 ? sqlcode (例:db2 ? sql0803) 注:code必须为4位数,不够4位,前面补0十一、bind命令:将应用程序与数据库作一捆绑,每次恢复数据库后,建议都要做一次bind(1) db2 bind br8200.bnd(2) /btp/bin/bndall /btp/bnd/btp/bin/bndall /btp/tran/bnd十二、查看数据库参数:db2 get dbm cfgdb2 get db cfg for btpdbs十三、修改数据库参数:db2 update db cfg for btpdbs using LOGBUFSZ 20db2 update db cfg for btpdbs using LOGFILSIZ 5120改完后,应执行以下命令使其生效:db2 stopdb2 start补充:db2 set schema btp 修改当前模式为"btp"db2 list tablespaces show detail 查看当前数据库表空间分配状况db2 list tablespace containers for 2 show detail 查看tablespace id=2使用容器所在目录db2 list applicationdb2 list db directory 列出所有数据库db2 list active databases 列出所有活动的数据库db2 list tables for all 列出当前数据库下所有的表db2 list tables for schema btp 列出当前数据库中schema为btp的表db2 list tablespaces show detail 显示数据库空间使用情况db2 list packages for alldb2 "import from tab76.ixf of ixf commitcount 5000 insert into achact"db2 "create table achact_t like achact"db2 "rename table achact_t to achact"db2 "insert into achact_t select * from achact where txndt>=(select lstpgdt from acmact where actno=achact.actno)"db2 get snapshot for dynaimic sql on jining删除一个实例:# cd /usr/lpp/db2_07_01/instance# ./db2idrop InstName列出所有DB2实例:# cd /usr/lpp/db2_07_01/bin# ./db2ilist为数据库建立编目$ db2 catalog db btpdbs on /db2catalog取消已编目的数据库btpdbs$ db2 uncatalog db btpdbs查看版本# db2level显示当前数据库管理实例$ db2 get instance设置实例系统启动时是否自动启动。

相关文档
最新文档