在執行如下命令時,需要首先在用戶端運行中輸入db2cmd進行初始化或者su到db2的執行個體下操作。
一、常識性命令
1、db2 connect to <資料庫名> --串連到本機資料庫名
db2 connect to <資料庫名> user <使用者名稱> using <密碼> --串連到遠端資料庫
2、 db2 force application all --強迫所有應用斷開資料庫連接
3、db2 backup db db2name<資料庫名稱> --備份整個資料庫資料
db2 restore db <db2name> --還原資料庫
4、db2 list application --查看所有串連(需要串連到具體資料庫才能查看)
5、db2stop --停止資料庫 db2start --啟動資料庫
6、create database <資料庫名> using codeset utf-8 territory CN --建立資料庫使用utf-8編碼
7、db2 catalog 命令
db2 catalog tcpip node <接點名稱> remote <遠端資料庫地址> server <連接埠號碼> --把遠端資料庫映射到本地接點一般為50000
db2 catalog db <遠端資料庫名稱> as <接點名稱> at node PUB11 --遠端資料庫名稱到本地接點
db2 CONNECT TO <接點名稱> user <使用者名稱> using <密碼> --串連本地接點訪問遠端資料庫
8、資料庫匯出
db2look -d <資料庫名> -u <使用者> -e -o <指令碼名稱>.sql --匯出資料庫的表結構,其中使用者空間一般為
db2admin/db2inst2
db2look -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 --修改頁編碼為1208
12、db2 describe table <表名> --查看錶結構
13、db2 list tables --查看資料庫中所有表結構
db2 list tables for system --列出所有系統資料表
14、db2 list tablespaces --列出資料表空間
15、fetch first 10 rows only --列出表中前10條資料
例如:select * from <表名> fetch first 10 rows only
16、coalesce(欄位名,轉換後的值) --對是null的欄位進行值轉換
例如:select coalesce(id,1) from <表名> --對錶中id如果為null轉換成1
二、匯入資料:
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 btpdbs
2、 db2move btpdbs export
db2look -d btpdbs -e -x [-a] -o crttbl.sql