出自:
http://blog.csdn.net/greener2000/
1. 啟動實(shí)例(db2inst1):
db2start
2. 停止實(shí)例(db2inst1):
db2stop
3. 列出所有實(shí)例(db2inst1)
db2ilist
5.列出當(dāng)前實(shí)例:
db2 get instance
4. 察看示例配置文件:
db2 get dbm cfg|more
5. 更新數(shù)據(jù)庫管理器參數(shù)信息:
db2 update dbm cfg using para_name para_value
6. 創(chuàng)建數(shù)據(jù)庫:
db2 create db test
7. 察看數(shù)據(jù)庫配置參數(shù)信息
db2 get db cfg for test|more
8. 更新數(shù)據(jù)庫參數(shù)配置信息
db2 update db cfg for test using para_name para_value
10.刪除數(shù)據(jù)庫:
db2 drop db test
11.連接數(shù)據(jù)庫
db2 connect to test
11.列出所有表空間的詳細(xì)信息。
db2 list tablespaces show detail
12.列出容器的信息
db2 list tablespace containers for tbs_id show detail
13.創(chuàng)建表:
db2 ceate table tb1(id integer not null,name char(10))
14.列出所有表
db2 list tables
12.插入數(shù)據(jù):
db2 insert into tb1 values(1,’sam’);
db2 insert into tb2 values(2,’smitty’);
13.查詢數(shù)據(jù):
db2 select * from tb1
14.數(shù)據(jù):
db2 delete from tb1 where id=1
15.創(chuàng)建索引:
db2 create index idx1 on tb1(id);
16.創(chuàng)建視圖:
db2 create view view1 as select id from tb1
17.查詢視圖:
db2 select * from view1
18.節(jié)點(diǎn)編目
db2 catalog tcp node node_name remote server_ip server server_port
19.察看端口號
db2 get dbm cfg|grep SVCENAME
20.測試節(jié)點(diǎn)的附接
db2 attach to node_name
21.察看本地節(jié)點(diǎn)
db2 list node direcotry
22.節(jié)點(diǎn)反編目
db2 uncatalog node node_name
23.數(shù)據(jù)庫編目
db2 catalog db db_name as db_alias at node node_name
24.察看數(shù)據(jù)庫的編目
db2 list db directory
25.連接數(shù)據(jù)庫
db2 connect to db_alias user user_name using user_password
26.數(shù)據(jù)庫反編目
db2 uncatalog db db_alias
27.導(dǎo)出數(shù)據(jù)
db2 export to myfile of ixf messages msg select * from tb1
28.導(dǎo)入數(shù)據(jù)
db2 import from myfile of ixf messages msg replace into tb1
29.導(dǎo)出數(shù)據(jù)庫的所有表數(shù)據(jù)
db2move test export
30.生成數(shù)據(jù)庫的定義
db2look -d db_alias -a -e -m -l -x -f -o db2look.sql
31.創(chuàng)建數(shù)據(jù)庫
db2 create db test1
32.生成定義
db2 -tvf db2look.sql
33.導(dǎo)入數(shù)據(jù)庫所有的數(shù)據(jù)
db2move db_alias import
34.重組檢查
db2 reorgchk
35.重組表tb1
db2 reorg table tb1
36.更新統(tǒng)計信息
db2 runstats on table tb1
37.備份數(shù)據(jù)庫test
db2 backup db test
38.恢復(fù)數(shù)據(jù)庫test
db2 restore db test
DB2數(shù)據(jù)庫使用
DML(Data Manipulation Language commands)數(shù)據(jù)操縱語言
DDL(Data Definition Language commands) 數(shù)據(jù)定義語言
TCC(Transaction Control commands) 事務(wù)控制語言
SCC(System Control commands ) 系統(tǒng)控制語言
一 DML數(shù)據(jù)操縱語言
(一)數(shù)據(jù)查詢命令
select <查詢內(nèi)容> From <表名>
where <條件> /*in,between,like%或_*/
group by<分組內(nèi)容>
having<組內(nèi)條件>
order by<排序內(nèi)容>[asc/desc];
(二)數(shù)據(jù)更新命令
1、數(shù)據(jù)插入命令
(1).具體的值插入表中
Insert into <表名> [(列名表)]
values<值表1>,<值表2>,<值表2>...
(注: 日期,字符型值加引號)
(2).將其它表滿足條件的數(shù)據(jù)插入到一個表中
Insert into <表名> [<列表名>] <select 子句>
2、數(shù)據(jù)修改命令
Update <表名> set <列名1>=<表達(dá)式1>,<列名2>=<表達(dá)式2>...
[where<條件>];
Update <表名> set <列名1>=(<select 子句>) [where<條件>];
3、數(shù)據(jù)刪除命令
Delete from <表名> [where<條件>];
二 DDL數(shù)據(jù)定義語言
(一)、基本數(shù)據(jù)類型
1.字符串
字符串為一個字節(jié)序列,字符串的長度為序列中的字節(jié)數(shù)。如果長度為零,則該字符串的值稱為空字符串。
CHAR(x) 是固定長度字符串。(1=<x<=254),缺省為1 。
VARCHAR(x) 可變長度字符 x<=4000,x>254不能用group by ,order by,distinct 和除
union all以外的任何設(shè)置操作。
GRAPHIC(x) 是固定圖形字符串。(1=<x<=127)
BLOB 二進(jìn)制字符串,是一個字節(jié)序列,用于保存非傳統(tǒng)數(shù)據(jù),如圖象、圖形、聲
音等數(shù)據(jù)。
2 數(shù)字 :所有數(shù)字都有符號和精度。精度是除開符號的位數(shù)或數(shù)字?jǐn)?shù)。
SMALLINT 小整數(shù),是精度為5位的兩字節(jié)整數(shù)。
INTEGER 大整數(shù),是精度為10位的四字節(jié)整數(shù)。
REAL 單精度浮點(diǎn)數(shù),是實(shí)數(shù)的32位近似值。
DOUBLE 雙精度浮點(diǎn)數(shù),是實(shí)數(shù)的64位近似值,DOUBLE也稱FLOAT。
DECIMAL(p,s) DECIMAL是一個十進(jìn)制數(shù)。小數(shù)點(diǎn)的位置由數(shù)字的 精度(p)和小數(shù)位(s)
確定。精度是數(shù)字的總位數(shù),必須小于32。小數(shù)位是小數(shù)部分?jǐn)?shù)字的位
數(shù)且總是小于或等于精度值。如果未指定精度和小數(shù)位,則十進(jìn)制值的
缺省精度為5,缺省小數(shù)位為0。
3 日期時間值 :日期時間值是日期、時間以及時間戳記的表示,日期時間值可以用于某些算術(shù)運(yùn)算和字符串運(yùn)算并且與某些字符串是相容的。
DATE 由三個部分構(gòu)成(年、月以及日)。
TIME 使用24小時制,分為三個部分(小時、分鐘以及秒)。
IMESTAMP 分為七個部分(年、月、日、小時、分鐘、秒以及微秒)。
4空值 空值是一個區(qū)別于所有非空值的特殊值。它意味著行中的那一列無任何其
它值。所有數(shù)據(jù)類型都存在空值。
(二)、數(shù)據(jù)定義
1、Create (創(chuàng)建)
u 創(chuàng)建表:
Create table [<模式名>.]<表名> (<列名1> <類型> [Null|Not null] [,<列
名2> <類型>...]
u 創(chuàng)建視圖:
Create view [<模式名>.]<視圖名> [<列名表>] as select 語句
u 創(chuàng)建別名:
Create alias [<模式名>.]別名 for [<模式名>.]表名/視圖名/別名
u 創(chuàng)建索引:
Create [unique] index <索引名> /*I_表名_字段名*/ on <表名>(<列名
>[asc|desc]
u 創(chuàng)建模式:
Create schema 模式名 authorization 權(quán)限名
2、Drop (摧毀)
u 摧毀表:
drop table [<模式名>.]表名
u 摧毀視圖:
drop view [<模式名>.]視圖名
u 摧毀別名:
drop alias [<模式名>.]別名
u 摧毀觸發(fā)器:
drop trigger [<模式名>.]觸發(fā)器名
u 摧毀索引:
drop index [<模式名>.]<索引名>
u 摧毀包:
drop package [<模式名>.]包名
3、Alter (變更)
u 增加表列:
Alter table [<模式名>.]<表名> add column [<列名1> <類型> [Null|Not null]]...
u 增加約束:
Alter table [<模式名>.]<表名> add constraint 列名 CHECK (約束)
u 刪除約束:
Alter table [<模式名>.]<表名> drop constraint 約束名
u 修改列類型:
Alter table [<模式名>.]<表名> alter column 列名 set data type <類型>
4、Grant (賦權(quán))
u 對[public/用戶/組] 賦于在表上的[all/select/insert/update/delete] 權(quán)限:
Grant [all/select/insert/update/delete] on [<模式名>.]表名to [public/用戶/
組];
u 對[public/用戶/組] 賦于在包上的[bind/execute/]權(quán)限:
Grant [bind/execute/] on package [<模式名>.][包名] to [public/用戶/組];
u 對[public/用戶/組] 賦于在索引上的[control]權(quán)限:
Grant control on index [<模式名>.]索引名 to [public/用戶/組]
5、Revoke (回收)
u 從public/用戶/組] 回收在表上的[all/select/insert/update/delete] 權(quán)限:
Revoke [all/select/insert/update/delete] on [表名] from [public/用戶/組];
u 從public/用戶/組] 回收在包上的[bind/execute/] 權(quán)限:
Revoke [bind/execute/] on package [<模式名>.][包名]from [public/用戶/組];
三 事務(wù)控制語言
1.事務(wù)提交命令: Commit;
2.事務(wù)回退命令: Rollback;
四 系統(tǒng)控制語言
1. 取消自動提交:
Update command options using c off;
2. 連接數(shù)據(jù)庫:
Connect to 數(shù)據(jù)庫名 user 用戶 using 密碼
3. 斷開數(shù)據(jù)庫連接:
Connect reset
Disconnect 數(shù)據(jù)庫名
4. 列出數(shù)據(jù)庫中的所有表:
List tables for all
5. 列出數(shù)據(jù)庫中的模式名為schema_name的所有表:
List tables for schema schema_name
6.查看表結(jié)構(gòu)
Describe table 模式名.表名
Describe select * from 模式名.表名
7.查看表的索引
Describe indexes for table 模式名.表名
五 函數(shù)
(一) 列函數(shù)
列函數(shù)對列中的一組值進(jìn)行運(yùn)算以得到單個結(jié)果值。
1.AVG
返回某一組中的值除以該組中值的個數(shù)的和
2.COUNT (*)
返回非空列值的行數(shù)。
3.MAX
返回一組值中的最大值
4.MIN
返回一組值中的最小值
5. MOD
求余
(二) 標(biāo)量函數(shù)
標(biāo)量函數(shù)對值進(jìn)行某個運(yùn)算以返回另一個值。下列就是一些由DB2通用數(shù)據(jù)庫提供的標(biāo)量函數(shù)的示例。
1.ABS
返回數(shù)的絕對值
2.HEX
返回值的十六進(jìn)制表示
3.LENGTH
返回自變量中的字節(jié)數(shù)(對于圖形字符串則返回雙字節(jié)字符數(shù)。)
4.YEAR
抽取日期時間值的年份部分
5.NULLIF(a,b)
如果a=b則值為空,否則值為a
6.COALESCE(a,b,c)
:返回第一個具有非空值的參數(shù)的值
7.UCASE(str)
小寫字符轉(zhuǎn)換成大寫字符
8.ICASE(str)
大寫字符轉(zhuǎn)換成小寫字符
9.LOCAT(str1,str2,n)
返回從第n個字符起,在str1中str2第一次出現(xiàn)的位置
10.SUBSTR(str,m,n)
返回從第m個字符起,,在str中的n個字符串
六 嵌入式SQL(SQLJ)
將SQL語句嵌入應(yīng)用程序時,必須按以下步驟預(yù)編譯應(yīng)用程序并將其與數(shù)據(jù)庫聯(lián)編:
1.創(chuàng)建源文件,以包含帶嵌入式 SQL 語句的程序
格式: # SQL{ SQL語句 } 。
2.連接數(shù)據(jù)庫,然后預(yù)編譯每個源文件。
語法: SQLJ 源文件名
例:
import java.sql.*;
import sqlj.runtime.*;
import sqlj.runtime.ref.*;
#sql iterator App_Cursor1 (String empno, String firstnme) ;
#sql iterator App_Cursor2 (String) ;
class App
{
static
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static void main(String argv[])
{
try
{
App_Cursor1 cursor1;
App_Cursor1 cursor2;
String str1 = null;
String str2 = null;
int count1;
Connection con = null;
String url = "jdbc:odbc:tese2";
DefaultContext ctx = DefaultContext.getDefaultContext();
if (ctx == null) {
try {
if (argv.length == 0) {
String userid ="tdl";
String passwd ="user";
con = DriverManager.getConnection(url, userid, passwd);
}
else if (argv.length == 2) {
// connect with default id/password
con = DriverManager.getConnection(url);
}
else {
System.out.println("\nUsage: java App [username password]\n");
System.exit(0);
}
con.setAutoCommit(false);
ctx = new DefaultContext(con);
}
catch (SQLException e) {
System.out.println("Error: could not get a default context");
System.err.println(e) ;
System.exit(1);
}
DefaultContext.setDefaultContext(ctx);
}
#sql cursor1 = { SELECT empno, firstnme from db2admin.employee };
System.out.println("Received results:");
while (cursor1.next()) {
str1 = cursor1.empno();
str2 = cursor1.firstnme();
System.out.print (" empno= " + str1);
System.out.print (" firstname= " + str2);
System.out.print ("\n");
}
cursor1.close();
#sql cursor2 = { SELECT firstnme from db2admin.employee where empno = :str1 };
System.out.println("Received results:");
while (true) {
#sql { FETCH :cursor2 INTO :str2 };
if (cursor2.endFetch()) break;
System.out.print (" empno= " + str1);
System.out.print (" firstname= " + str2);
System.out.print ("\n");
}
cursor2.close();
// rollback the update
System.out.println("\n\nRollback the update...");
#sql { ROLLBACK work };
System.out.println("Rollback done.");
}
catch( Exception e )
{
e.printStackTrace();
}
}
}
注:本程序采用JDBCODBC橋的方式訪問數(shù)據(jù)庫,必須配置ODBC數(shù)據(jù)源。
七 觸發(fā)器
建一個觸發(fā)器,應(yīng)包含以下部分:
觸發(fā)器名字
觸發(fā)器觸發(fā)事件: insert,delete,update
激活時間: before,after
粒度: for each statement,for each row
過渡變量:
old row:表示觸發(fā)事件之前被修改的值:
new row表示觸發(fā)事件之后被修改的值
old table表示觸發(fā)事件之前全部被修改行的一個只讀假想表
new table表示觸發(fā)事件之后全部被修改行的一個假想表
觸發(fā)條件: 由WHEN開始,可包含一個或多個謂詞,可包含過渡變量和子查詢
觸發(fā)體: 由一個或多個SQL語句組成
例:
CREATE TRIGGER REORDER
AFTER UPDATE OF ON_HAND, MAX_STOCKED ON PARTS
REFERENCING NEW AS N_ROW
FOR EACH ROW MODE DB2SQL
WHEN (N_ROW.ON_HAND < 0.10 * N_ROW.MAX_STOCKED
AND N_ROW.ORDER_PENDING = 'N')
BEGIN ATOMIC
VALUES(ISSUE_SHIP_REQUEST(N_ROW.MAX_STOCKED -
N_ROW.ON_HAND,
N_ROW.PARTNO));
UPDATE PARTS SET PARTS.ORDER_PENDING = 'Y'
WHERE PARTS.PARTNO = N_ROW.PARTNO;
END
八 存儲過程
存儲過程主要通過”Stored Procedure Builder”來建立,
(一)對存儲過程的調(diào)用分三部分:
1.連接(與數(shù)據(jù)庫建立連接)
Class.forName("COM.ibm.db2.jdbc.net.DB2Driver").newInstance();
Connection con=DriverManager.getConnection(url,user,password);
2。注冊輸出參數(shù)
cs.registerOutParameter (3, Types.INTEGER);
3。調(diào)用存儲過程:
CallableStatement cs=con.prepareCall("{call store_name(參數(shù),參數(shù),參數(shù))}");
(二)調(diào)用舉例:
import java.net.URL;
import java.sql.*;
class test2
{
public static void main(String args[])
{
String url = "jdbc:db2://wellhope/sample";
String user="db2admin";
String password="db2admin";
try
{
Class.forName("COM.ibm.db2.jdbc.net.DB2Driver").newInstance();
//與數(shù)據(jù)庫建立連接
Connection con=DriverManager.getConnection(url,user,password);
checkForWarning(con.getWarnings());
DatabaseMetaData dma=con.getMetaData();
String str="This is a string";
//int hashcode=str.hashCode();
//System.out.println("Hashcode "+hashcode);
//創(chuàng)建Statement對象,用于執(zhí)行SQL語句
Statement stmt=con.createStatement();
//創(chuàng)建CallableStatement對象,用于執(zhí)行存儲過程
CallableStatement cs=con.prepareCall("{call PRO_YHDL1(?,?,?)}");
//注冊輸出參數(shù)
cs.registerOutParameter (3, Types.INTEGER);
int result = 0;
cs.setString(1,"123");
cs.setString(2,"123");
cs.execute();
result = cs.getInt (3);
dispResultSet(result);
cs.close();
con.close();
}
catch(SQLException ex)
{
System.out.println("\n * * * SQLException caught * * * \n");
while(ex!=null)
{
System.out.println("SQLState: "+ex.getSQLState());
System.out.println("Message: "+ex.getMessage());
System.out.println("Vendor: "+ex.getErrorCode());
ex=ex.getNextException();
System.out.println("");
}
}
catch(java.lang.Exception ex)
{
ex.printStackTrace();
}
}
(三)存儲過程舉例:
Pro_yhdl1是一個存儲過程,它的功能是從數(shù)據(jù)庫表YHDL中取出PWD:
import java.sql.*;
public class Pro_yhdl1
{
public static void pro_yhdl1 ( String m_id,
String m_pwd,
int[] result ) throws SQLException, Exception
{
// Get connection to the database
Connection con = DriverManager.getConnection("jdbc:default:connection");
PreparedStatement stmt = null;
ResultSet rs = null;
String sql;
String m_password="";
sql = "SELECT"
+ " DB2ADMIN.YHDL.PWD"
+ " FROM"
+ " DB2ADMIN.YHDL"
+ " WHERE"
+ " ("
+ " ( "
+ " DB2ADMIN.YHDL.ID = '"+m_id.trim()+"'"
+ " )"
+ " )";
stmt = con.prepareStatement( sql );
rs = stmt.executeQuery();
// Access query results
while (rs.next())
{
m_password=rs.getString(1);
m_password=m_password.trim();
if (rs.wasNull())
System.out.print("NULL");
else
System.out.print(m_password);
}
if(m_password.equals(m_pwd.trim()))
{
result[0] =1;
}
else
{
result[0] =0;
}
// close open resources
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (con != null) con.close();
// set return parameter
//result[0] = result[0];
}
}
九 JAVA數(shù)據(jù)庫鏈接(JDBC)
DB2 的 Java 支持包括 JDBC,一個以供應(yīng)商為中心的動態(tài) SQL 接口,它通過標(biāo)準(zhǔn)的 Java方法提供對應(yīng)用程序的數(shù)據(jù)存取。JDBC 與 DB2 CLI 相似之處在于您不必預(yù)編譯或聯(lián)編 JDBC 程序。使用 JDBC 編寫的應(yīng)用程序只使用動態(tài) SQL。
JDBC編程步驟:
1建立與數(shù)據(jù)庫的連接:
Class.forName("Com.ibm.db2.jdbc.net.DB2Driver");
connection con=DriverManager.getConnection(url);
2.創(chuàng)建Statement對象:
Statement stmt=con.createStatement();
3執(zhí)行查詢語句:
ResultSet rs=stmt.execQuery("SQL語句");
4.獲取和設(shè)置選項:
ResultSetMetaData rsmd=rs.getMetaData();
int numCols=rsmd.getColumnCount()獲取結(jié)果集總列數(shù);
rsmd.getColumnLabel(i))獲取記錄值;
setMaxRows :設(shè)置結(jié)果集能容納的最多行數(shù).
setQueryTimeout:設(shè)置一個語句執(zhí)行等待的時間.
setEscapeProcessing:通知驅(qū)動程序如何處理轉(zhuǎn)義字符.
5.關(guān)閉Statement
stmt.clost();
十 調(diào)用層接口(CLI)
CLI不是一種新的查詢語言,它只不過是應(yīng)用程序可利用SQL語句去提交事務(wù)處理的一種簡單接口,對數(shù)據(jù)庫的查詢和修改,仍要使用SQL語言編寫,包括CLI函數(shù)的調(diào)用。
調(diào)用層接口(CLI)為DB2所提供的處理動態(tài)SQL語句的兩種機(jī)制之一,即在應(yīng)用程序首次運(yùn)行時,動態(tài)SQL語句提交給數(shù)據(jù)庫系統(tǒng),CLI依賴一組函數(shù)調(diào)用,可嵌入主語言中.
posted on 2006-02-13 13:07
zjw_albert 閱讀(534)
評論(1) 編輯 收藏