untitled

Similar documents
ebook45-5

Microsoft Word - 01.DOC

untitled

Java

epub 61-2

untitled

FY.DOC

目錄

附录J:Eclipse教程

1. 访 问 最 新 发 行 公 告 信 息 jconnect for JDBC 访 问 最 新 发 行 公 告 信 息 最 新 版 本 的 发 行 公 告 可 以 从 网 上 获 得 若 要 查 找 在 本 产 品 发 布 后 增 加 的 重 要 产 品 或 文 档 信 息, 请 访

Microsoft Word - CIN-DLL.doc

四川省普通高等学校

关 于 我 姓 名 : 葛 云 杰 网 名 :Dylan Oracle OCM Oracle 用 户 组 年 轻 专 家 中 国 OCM 联 盟 成 员 山 东 Oracle 用 户 组 联 合 创 始 人 齐 鲁 IT 联 盟 联 合 创 始 人 软 件 研 发 工 程 师 具 有 十 年 以 上

ebook140-8

软件测试(TA07)第一学期考试

基于CDIO一体化理念的课程教学大纲设计

习题1

尽 管 Java 语 言 是 在 C++ 语 言 基 础 上 发 展 起 来 的, 但 与 C++ 不 同,Java 是 一 种 纯 粹 的 面 向 对 象 语 言 (Object-oriented language) 在 Java 世 界 中, 所 有 事 物 都 是 Object 1. 通 过

<4D F736F F D20C9CFBAA3CAD0BCC6CBE3BBFAB5C8BCB6BFBCCAD4C8FDBCB6BFBCCAD4B4F3B8D95FBDA8D2E9B8E55F5F E646F63>

尽 管 Java 语 言 是 在 C++ 语 言 基 础 上 发 展 起 来 的, 但 是 有 别 于 C++,Java 是 一 种 纯 粹 的 面 向 对 象 语 言 (Object-oriented language) 在 像 Java 这 样 纯 粹 的 面 向 对 象 语 言 中, 所 有

一 個 SQL Injection 實 例 的 啟 示 頁 2 / 6 因 此, 在 知 名 網 站 上 看 到 SQL Injection, 讓 人 驚 心, 卻 不 意 外 網 站 專 案 外 包 是 目 前 業 界 的 常 態, 而 在 價 格 取 勝 的 制 度 下, 低 價 得 標 的 S

数 据 库 系 统 基 础 2/54 第 6 章 数 据 库 管 理 与 维 护

<4D F736F F D A617661B7C3CECA53514C BEDDBFE2B5C4C9E8BCC6D3EBCAB5CFD62E646F63>

Symantec™ Sygate Enterprise Protection 防护代理安装使用指南

《面向对象程序设计A》课程教学大纲Ⅱ4

提问袁小兵:

Microsoft PowerPoint - course2.ppt

上海市教育考试院关于印发新修订的

SiteView技术白皮书

untitled

ebook45-4

幻灯片 1

ebook 96-16

學 科 100% ( 為 單 複 選 題, 每 題 2.5 分, 共 100 分 ) 1. 請 參 閱 附 圖 作 答 : (A) 選 項 A (B) 選 項 B (C) 選 項 C (D) 選 項 D Ans:D 2. 下 列 對 於 資 料 庫 正 規 化 (Normalization) 的 敘

chp6.ppt

第 15 章 程 式 編 写 語 言 15.1 程 式 編 写 語 言 的 角 色 程 式 編 寫 語 言 是 程 式 編 寫 員 與 電 腦 溝 通 的 界 面 語 法 是 一 組 規 則 讓 程 式 編 寫 員 將 字 詞 集 合 起 來 電 腦 是 處 理 位 元 和 字 節 的 機 器, 與

1 SQL Server 2005 SQL Server Microsoft Windows Server 2003NTFS NTFS SQL Server 2000 Randy Dyess DBA SQL Server SQL Server DBA SQL Server SQL Se

9, : Java 19., [4 ]. 3 Apla2Java Apla PAR,Apla2Java Apla Java.,Apla,,, 1. 1 Apla Apla A[J ] Get elem (set A) A J A B Intersection(set A,set B) A B A B

<4D F736F F D D342DA57CA7DEA447B14D2DA475B57BBB50BADEB27AC3FEB14DA447B8D5C344>

Microsoft Word - PS2_linux_guide_cn.doc

ebook204-2

XXXXXXXX

科学计算的语言-FORTRAN95

全国计算机技术与软件专业技术资格(水平)考试

<4D F736F F D20BBB7BEB3D0C5CFA2CFB5CDB3CAFDBEDDBFE2B7C3CECABDD3BFDAB9E6B7B6A3A8B1A8C5FAB8E5A3A E646F63>

untitled

内 容 提 要 将 JAVA 开 发 环 境 迁 移 到 Linux 系 统 上 是 现 在 很 多 公 司 的 现 实 想 法, 而 在 Linux 上 配 置 JAVA 开 发 环 境 是 步 入 Linux 下 JAVA 程 序 开 发 的 第 一 步, 本 文 图 文 并 茂 地 全 程 指

f2.eps

ME3208E2-1.book

untitled

A API Application Programming Interface 见 应 用 程 序 编 程 接 口 ARP Address Resolution Protocol 地 址 解 析 协 议 为 IP 地 址 到 对 应 的 硬 件 地 址 之 间 提 供 动 态 映 射 阿 里 云 内

二 Synchronized 1. Java 语 言 的 关 键 字, 当 它 用 来 修 饰 一 个 方 法 或 者 一 个 代 码 块 的 时 候, 能 够 保 证 在 同 一 时 刻 最 多 只 有 一 个 线 程 执 行 该 段 代 码 2. 当 两 个 并 发 线 程 访 问 同 一 个

入學考試網上報名指南

13 根 据 各 种 网 络 商 务 信 息 对 不 同 用 户 所 产 生 的 使 用 效 用, 网 络 商 务 信 息 大 致 可 分 为 四 级, 其 中 占 比 重 最 大 的 是 ( A ) A 第 一 级 免 费 信 息 B 第 二 级 低 收 费 信 息 C 第 三 级 标 准 收 费

詞 彙 表 編 號 詞 彙 描 述 1 預 約 人 資 料 中 文 姓 名 英 文 姓 名 身 份 證 字 號 預 約 人 電 話 性 別 2 付 款 資 料 信 用 卡 別 信 用 卡 號 信 用 卡 有 效 日 期 3 住 房 條 件 入 住 日 期 退 房 日 期 人 數 房 間 數 量 入

Microsoft Word - 11.doc

高 职 计 算 机 类 优 秀 教 材 书 目 * 序 号 书 号 (ISBN) 书 名 作 者 定 价 出 版 / 印 刷 日 期 ** 配 套 资 源 页 码 计 算 机 基 础 课 计 算 机 应 用 基 础 刘 升 贵 年 8 月

VB程序设计教程

Acrobat Distiller, Job 3

chp1

多層次傳銷與獎金系統

目 录 简 介.3 ` 体 系 结 构...4 数 据 层...5 数 据 连 接 器...6 Tableau Server 组 件...7 网 关 / 负 载 平 衡 器...8 客 户 端 :Web 浏 览 器 和 移 动 应 用 程 序...8 客 户 端 :Tableau Desktop..

建 立 数 据 库 档 案 用 sqlite3 建 立 数 据 库 的 方 法 很 简 单, 只 要 在 shell 下 键 入 ( 以 下 $ 符 号 为 shell 提 示 号, 请 勿 键 入 ): $ sqlite3 foo.db 如 果 目 录 下 没 有 foo.db,sqlite3 就

(CIP) Web /,. :, ISBN X.W T P393.4 CIP (2004) Web ( ) ( / ) : * 787

《计算机导论》实验教学大纲

《大话设计模式》第一章

Microsoft Word htm

JAVA编码规范

第1章 QBASIC语言概述

<4D F736F F D D352DBED6D3F2CDF8D7E9BDA8D3EBB9DCC0EDCFEEC4BFBDCCB3CCD5FDCEC42E646F63>

(procedure-oriented)?? 2

CANVIO_AEROCAST_CS_EN.indd

經濟統計資料庫管理資訊系統

Microsoft PowerPoint - Ch6

CH01.indd

教案模板4-2

Oracle Database 10g: SQL (OCE) 的第一堂課

大学计算机基础B.doc

GoFlex Home UG Book.book

Transcription:

Java

JDBC JAVA JAVA JDBC JDBC JDVA

1 Java... 1 1.1 Java... 1 1.2 Java... 2 1.3 Java... 3 1.4 Java... 5 1.5... 9 2 Java... 10 2.1 JDK... 10 2.2 JDK... 10 2.3 JDK... 13 2.... 13 3 Java... 15 3.1... 15 3.2 Java... 16 3.3 Java... 17 3.4 Java... 18 3.5 Java... 18 3.6 Java... 19 3.7 Java... 23 3.8 Java... 27 3.9 Java... 31 3.10 Java... 36 3.11 Java... 38 3.12... 42 4... 43 4.1... 43 4.1.1... 43 4.1.2... 43 4.1.3... 44 4.1.4... 45 4.2 SQL... 46 4.2.1 SQL... 46 4.2.2 SQL... 46

VI 4.3 SQL... 58 4.4... 62 4.5 SQL... 67 4.6... 77 4.7... 81 5 JDBC... 82 5.1 JDBC... 82 5.2 Java... 83 5.3 SQL... 84 5.4 JDBC ODBC API... 84 5.5 JDBC... 85 5.6 JDBC... 86 5.7 JDBC... 87 5.8 JDBC... 89 5.9... 89 6 JDBC... 90 6.1... 90 6.2 JDBC... 95 6.3... 101 7 JDBC... 102 7.1... 102 7.1.1... 102 7.1.2... 103 7.1.3 Statement... 104 7.2... 106 7.3 ResultSet... 114 7.4 JDBC... 118 7.5 JDBC... 125 7.6 PreparedStatement... 131 7.6.1 PreparedStatement... 131 7.6.2... 132 7.6.3 PreparedStatement... 138 7.7 CallableStatement... 140 7.7.1 CallableStatement... 140 7.7.2... 141 7.7.3 CallableStatement... 142 7.8... 144 8 JDBC... 146 8.1 JDBC... 146 8.2 JDBC... 148

VII 8.3... 150 8.3.1... 150 8.3.2... 153 8.4... 155 9... 156 9.1 Servlet... 156 9.2 Servlet... 156 9.3 Servlet... 157 9.4 Servlet... 157 9.5 Servlet... 158 9.6 Servlet... 160 9.7 Servlet... 163 9.8... 166 10 Web... 167 10.1... 167 10.2 Servlet... 177 10.3... 184 11 Web... 186 11.1 Servlet... 186 11.2 Servlet... 188 11.3 Servlet... 190 11.4 Servlet... 193 11.5 Servlet... 196 11.6 Servlet PreparedStatement... 199 11.7 Servlet CallableStatement... 203 11.8... 206 12 Servlet... 208 12.1... 208 12.2... 220 12.3... 223 12.4... 275 13 Java Server Pages... 276 13.1 JSP... 276 13.2 JSP... 277 13.2.1... 277 13.2.2 JSP... 278 13.3 JSP... 292 13.4 JSP JDBC... 330 13.5... 332 14 JDBC API... 333

VIII 14.1 Class DriverManager... 333 14.2 Interface Driver... 336 14.3 Class DriverPropertyInfo... 337 14.4 Interface Connection... 339 14.5 Interface PreparedStatement... 344 14.6 Interface ResultSet... 352

1 Java 1.1 Java 1 Java 10 15 Java Java Sun WWW WWW Java Java Internet PC Sun Java 1991 Sun Green World Wide Web James Gosling 1957 1984 Sun Microsystem IBM SunNeWs C EMACS COSMACS Gosling CPU RISC 8086 80586 2 Java Gosling C Gosling C 1991 6?Gosling Oak Java Oak Sun Java Gosling Java Gosling Virtual Machine Code Java Java Gosling SunNeWs NeWs Postscript Postscript Patrick Naughton Sun Open Windows

2 Java Naughton 17 Java Sun 75 Sun Java Sun ScottMcNealy BillJoy Java 3 Java IT 1994 WWW Gosling WWW Gosling Java Web Naughton JonathanPayne 1994 WebRunner WebRunner HotJava Java WebRunner HotJava 1995 5 23 Java Java1.0 1996 1.2 Java Java Sun Internet Wintel Internet Java Java (1) Java IBM, Apple, DEC, Adobe, SiliconGraphics,HP,Oracel,Toshiba Microsoft Java (2) Java Borland Java Latte Borland Java PC Sun Java JavaWorkshop Illustra,Sysbase,Versant,Oracle CGI HTML Java HTML Java (3) Intranet Java Intranet Internet Intrnet Web ( Java Applet) WWW Java Sun JDK(JavaDevelopKit) JWS(JavaWorkshop) Java Java Java C++

1 Java 3 1.3 Java Java Java 1 Java Java (1) Java C++ C++ Java C C++ C++ Java (2) Java C++ (3) Java 2 Java Java C Java Java SmallTalk SmallTalk 3 Java HTTP FTP TCP/IP Java URL Internet Java 4 Java Java Java Java Java Null 5 Java Java Java Java Solaris2.4(SPARC),Win32 (Windows95 WindowsNT) Java byte-code 6 Java Java C++ Java Java

4 Java 7 byte-code 8 ClassLoader build-in( ) 9 Java Java Java Windows3.1 (Integer) 16bits Windows95 32bits DECAlpha 64bits Intel486 32bits Java Java byte8-bit short16-bit int32-bit long64-bit float32-bitieee754 double32-bitieee754 char16-bitunicode Java CPU 8 64 / Java Java Java POSIX ANSIC Java 10 Java ( ) 11 Java Sun 30 C/C++ 12 Java Java C C++ (UNIX,Windows,Macintosh ) Java HTML 13 Java C++ C++

1 Java 5 Java Java Java Java Java 1.4 Java Java 1 JavaApplet Internet Java Java Applet,Java Java Java Java Javaapplet, WWW HTML, applet Web, Java Internet Applet, Applet Javaapplet Java,, (UI) Java Applet,,, applet : Applet Applet Applet Unix, Applet,, DLL Java Applet 1.1 2 Java Java GUI C/C++ Hello World 1.2

6 Java 1.1 Java Applet 1.2 Java GUI 1.3~ 1.5 3 Java Serverlet Java 1.6 1.7 Servlet Servlet

1 Java 7 1.3 Metal GUI 1.4 Motiff GUI 1.5 Windows GUI

8 Java 1.6 1.7 4 JSP ASP ASP ASP ASP HTML CGI ASP (1) Windows Unix Windows NT ASP (2) Java JSP ASP Java Beans Java Web JSP JSP 1.8 JSP

1 Java 9 1.8 Jsp Java Java 1.5 1 Java Java 2 Java Java C++ C++ 3 C/C++ Java Java Java C/C++ 4 Java Java C/C++ Java 5 Java Java Java Unix Solaries AIX

2 Java 2.1 JDK Java JDK Java JDK Java JDK Java JavaAPI Java JavaAPI I/O JavaAPI I/O Java I/O Java JDK : Javac Java Java Java Java Java Appletviewer HTML Java Java Javadoc Java HTML Jdb Java Javah Java C Java C Javap Java 2.2 JDK JDK 2.1 JDK, JDK, Next 2.2 JDK Next 2.3 C: jdk1.3.0_01 Browse Next 2.4 JDK

2 Java 11 (1) Programe Files JDK java.exe Javac.exe Javasoc.exe 2.2 (2) Native Interface Header Files Java (3) Old Native Interface Header Files JDK

12 Java Java (4) Demos JDK Java (5) Java Source Java Next JDK 2.3 2.4

2 Java 13 2.3 JDK JDK JDK JDK DOS Autoexec.bat set path=c:\jdk1.3.0_01\bin c:\jdk1.3.0_01 Path Java.exe command.com c:\jdk1.3.0_01\bin java.exe DOS set path=c:\jdk1.3.0_01\bin 2.5 2.5 Autoexec.bat JDK Java 2.4 1 JDK Sun Javasoft http://www.javasoft.com

14 Java 2 JDK JDK CLASS_PATH BIN JDK 3 4 java Applet AppletView 5 JDK JDK Sun

3 Java 3.1 HelloWorld Java HelloWorld Java publicclasshelloworld /**ThisroutineiscalledfirstbytheJavainterpreter. Itprintsamessagetotheconsole.*/ publicstaticvoidmain(string[]argv) /*javadocwillignorethiscomment*/ System.out.println("HelloWorld"); 3.1 3.1 Hello World C/C++ Java main() Java main publicstatic

16 Java Java JavaApplication Java Main String C/C++ Java String C/C++ out java.lang.system println println Java 3.2 Java 1 Java : integer( ),floating( ),point( ),Boolean( ),CharacterorString( ) integer 1 10 0X86 8bitsbyte 16bitsshort 32bitsint 64bitslong floating 6.37 3.7E15 3e8 32bitsfloat 64bitsdouble Boolean true false Character a B X String Java 2 chars[]; int[]array; intblock[][]=newint[2][3], Java,, length inta[][]=newint[10][3]a.length/*10*/a[0].length/*3 Java (1) intlist[]=newint[50]; (2) Stringnames[]="Java","Database","Major","Application"; :

3 Java 17 String names[]; names=new String[4]; names[0]=new String("Chenji"); names[1]=new String("Yuan"); names[2]=new String("Chun"); names[3]=new String("Yang"); intname[50];// new intname[];for(inti=0;i<9;i++)name[i]=i; 3.3 Java Java C++, 1 // switch (i) case 0: // divided by zero int zero = 0; k = 911 / zero; break; case 1: // array index out of bound int[] c = new int[2]; k = c[9]; break; 2 /* */ /** TestDrive -- A test file for demonstration of the JDK. */ public class TestDrive /** This routine is called first by the Java interpreter. It prints a message to the console. */ public static void main(string[] argv) /* javadoc will ignore this comment */ System.out.println("JDK Test Drive"); 3 Javadoc Java Javadoc

18 Java @ /** * Applet * Applet @see java.applet.applet @author XXX @version 3.0 */ class HiApplet extends Applet /** *@this method takes two parameters *@param key is the name of the symbol to store *@parameter value is what to store associated with this key */ void put(string key,object value) 3.4 Java Java, _,$,, C/C++ abc m_nfalg _ahd221 Java abstract continue for new switch boolean default goto null synchronized break do if package this byte double implements private threadsafe byvalue else import protected throw case extends instanceof public transient catch false int return true char final interface short try class finally long static void const float native super while cast future generic inner operator outer rest var 3.5 Java Java C/C++ 3-1

3 Java 19 3-1 Java 3.6 Java Java C/C++, 3-2~ 3-6 3-2 Java + += - -= * *= / /= % %= ++ -- 3-3 Java ~ &= & = ^= ^ >>= >> >>> 0 >>>= 0 << <<= 3-4 ==!= > < >= <=

20 Java 3-5 & &= = ^ ^= == &&!=!?: If then else 3-6 A B A False False False False False True True False True False True False False True True False True True True true true true False False. [ ] () ++ --! * / % + - << >> >>> < > <= >\ ==! = & ^ &&? : = op =, Java instanceof if (myobject instanceof MyClass)MyClass anothermyobject=(myclass) myobject; myobject MyClass class BasicMath public static void main(string args[]) int a=1+1; int b=a*3; int c=b/4; int d=b-a; int e=-d; System.out.println( ); System.out.println( a= +a); System.out.println( b= +b); System.out.println( c= +c); System.out.println( d= +d);

3 Java 21 System.out.println("e="+e); a+=5; b*=4; c+=a*b; c%=6; System.out.println("a+="+a); System.out.println("b*="+b); System.out.println("c%="+c); c=++b; d=a++; System.out.println("c="+c); System.out.println("d="+d); BasicMath.java 3.2 3.2 : class Bit public static void main(string args[]) String binary[] = "0000","0001","0010","0011","0100","0101", "0110","0111","1000","1001","1010","1011",

22 Java "1100,1101,1110,1111", ; int a=3; //0011 in binary int b=6; //0110 in binary int c=a b; int d=a&b; int e=a^b; int f=(~a & b) (a&~b); int g=~a & 0x0f; System.out.println(" a=" + binary[a]); System.out.println(" b=" + binary[b]); System.out.println(" c=" +binary[c]); System.out.println(" d=" +binary[d]); System.out.println(" e=" +binary[e]); System.out.println(" f=" + binary[f]); System.out.println(" g=" + binary[g]); Bit.java (1) (2) Java.exe.class 3.3 3.3 B00l

3 Java 23 3.7 Java Java C/C++ 1 (1) if/else if (Boolean) statemanets; else statements; (2) switch switch(expr1) case expr2: statements; break; case expr3: statements; break; default: statements; break; 2 (1) for for (init expr1;test expr2;increment expr3) statements; (2) While While(Boolean)

24 Java statements; (3) Do do statements; while (Boolean); 3 break [label] ; continue [label] ; reutrn expr; label:statement; express statements Label class FinallyTest public static void main(string[] args) outer_loop: for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) try System.out.println("try before if: i=" + i + ", j=" + j); if ((i == 0) && (j == 1)) continue; else if ((i == 0) && (j == 2)) continue outer_loop; else if ((i == 1) && (j == 0)) break; else if ((i == 2) && (j == 1)) break outer_loop; System.out.println("try after if: i=" + i + ", j=" + j); finally System.out.println("finally: i=" + i + ", j=" + j

3 Java 25 + "\n"); 3.4 3.4 switch : public class Fenshu public static void main(stringargs[]) System.out.println("\n**firstsituation**"); Char fenshu='c';//normaluse switch(fenshu) case'a': System.out.println(fenshu+"is85 100"); break; case'b': System.out.println(fenshu +"is70 84"); break; case'c': System.out.println(fenshu +"is60 69"); break;

26 Java case'd': System.out.println(fenshu +"is 60"); break; default: System.out.println("inputerror"); System.out.println("\n**secondsituation**"); fenshu ='A'; createrrorwithoutbreakstatement switch(fenshu) case'a': System.out.println(fenshu +"is85 100"); case'b': System.out.println(fenshu +"is70 84"); case'c': System.out.println(fenshu +"is60 69"); case'd': System.out.println(fenshu +"is 60"); default: System.out.println("inputerror"); System.out.println("\n**thirdsituation**"); fenshu ='B'; severalcasewithsameoperation switch(fenshu) case'a': case'b': case'c': System.out.println(grade+"is =60"); break; case'd': System.out.println(fenshu +"is 60"); break; break; default: System.out.println("inputerror"); 3.5

3 Java 27 3.5 switch 3.8 Java,,, 1 1 : type arrayname[]; (type) Java, int,char,byte (class ), arrayname,[] : int Array[];, C C++,Java, [],,, new, : arrayname=new type[arraysize];,arraysize : int Array=new int[3]; 3 int,, : type arrayname=new type[arraysize]; : int Array=new int[3];

28 Java 2, new, : arrayname[index] index, a[3],b[i](i ),c[6*i] C/C++ 0 Java 0, 1 intarray, 3, int Array[0],int Array[1],int Array[2] : int Array[3], C C++,Java, length, :intarray.length intarray public class ArrayTest public static void main(stringargs[]) int i; int a[]=new int[5]; for(i=0;i 5;i++) a[i]=i; for(i=a.length-1;i =0;i--) System.out.println("a["+i+"]="+a[i]); 3.6 3.6

3 Java 29 3 int a[]=1,2,3,4,5; int a[3]; a[0]=1; a[1]=2; a[2]=3; 2 Java C/C++ 1 : type arrayname[arraysize1][arraysize2][arraysize3] ; : int Array[][];,, new,, :, : int a[][]=new int[2][3];,, : int a[][]=new int[2][]; a[0]=new int[3]; a[1]=new int[3]; (2), :arrayname[index1][index2] index1 index2,, a[2][3], 0 (3) int a[][]=2,3,1,5,3,4; 3 2,

30 Java public class MatrixMultiply public static void main(string args[]) inti,j,k; int a[][]=new int[2][3]; int b[][]=1,5,2,8,5,9,10,-3,2,7,-5,-18; int c[][]=new int[2][4]; for(i=0;i 2;i++) for(j=0;j 3;j++) a[i][j]=(i+1)*(j+2); for(i=0;i 2;i++) for(j=0;j 4;j++) c[i][j]=0; for(k=0;k 3;k++) c[i][j]+=a[i][k]*b[k][j]; System.out.println("\n***MatrixA***"); for(i=0;i 2;i++) for(j=0;j 3;j++) System.out.print(a[i][j]+""); System.out.println(); System.out.println("\n***MatrixB***"); for(i=0;i 3;i++) for(j=0;j 4;j++) System.out.print(b[i][j]+""); System.out.println(); System.out.println("\n***MatrixC***"); for(i=0;i 2;i++) for(j=0;j 4;j++) System.out.print(c[i][j]+""); System.out.println(); 3.7

3 Java 31 3.7 3.9 Java Java Java Java class classname extends superclassname type instance-variable1; type instance-variable2;... type instance-variablen; type methodname1(parameter-list) method-body; type methodname2(parameter-list) method-body;... type methodnamen(parameter-list)

32 Java method-body; classname SuperClassname Extends public Private Private protected 3-7 3-7 Private Private Protected Public Y Y Y Y N Y Y Y N Y N Y N N N Y N N N Y class PointTest public static void main(string[] args) MyPoint mp = new MyPoint(4,3); Point p = new Point(11); Point q = mp; mp.x = 5; mp.y = 12; System.out.println("\n\tData Member Access Test:\n"); System.out.println("mp = (" + mp.x + ", " + mp.y + ")"); System.out.println(" p = (" + p.x + ", " + p.y + ")"); System.out.println(" q = (" + q.x + ", " + q.y + ")"); System.out.println("\n\tCasting Test:\n"); System.out.println("(Point) mp = (" + ((Point) mp).x + ", " + ((Point) mp).y + ")"); System.out.println("(MyPoint) q = (" + ((MyPoint) q).x + ", " + ((MyPoint) q).y + ")"); System.out.println("\n\tMethod Member Access Test:\n"); System.out.println("mp.length() = " + mp.length());

3 Java 33 System.out.println(" p.length() = " + p.length()); System.out.println(" q.length() = " + q.length()); System.out.println("mp.distance() = " + mp.distance()); System.out.println("\n\tCasting Test:\n"); System.out.println("((Point) mp).length() = "+((Point)mp).length()); System.out.println("((Point) q).length() = "+((Point) q).length()); System.out.println("((MyPoint) q.distance() = " + ((MyPoint)q).distance( )); class Point int x; int y; Point(int x, int y) this.x = x; this.y = y; Point(int x) this(x, 0); Point() this(0, 0); double length() return Math.sqrt(x * x + y * y); class MyPoint extends Point int x; int y; MyPoint(int x, int y) this.x = super.x = x; this.y = super.y = y; double length() return Math.sqrt(x * x + y * y); double distance() return Math.abs(length() - super.length());

34 Java 3.8 3.8 This Java this this Super,,, Java super Java,this, this,super super : (1), : super.variable (2), : super.method([paramlist]); (3), : super([paramlist]); super, class superclass

3 Java 35 int x; superclass() x=3; System.out.println("insuperClass:x="+x); void dosomething() System.out.println("insuperClass.doSomething()"); class subclass extends superclass int x; subclass() super(); x=5; System.out.println("insubClass:x="+x); void dosomething() super.dosomething(); System.out.println("insubClass.doSomething()"); System.out.println("super.x="+super.x+"sub.x="+x); public class inheritance public static void main(string args[]) subclass subc=new subclass(); subc.dosomething(); 3.9 Java Java Java

36 Java 3.9 3.10 Java errno errno?reg; C goto Java Java Exception Exception Java 5 try,catch,throw,throws finally try finally try statements catch(exceptiontype1) error handle statements catch(exceptiontype2e)

3 Java 37 error handle throw(e); finally finally handler class ExceptionTest public static void main(string[] args) for (int i = 0; i < 4; i++) int k; try switch (i) case 0: // divided by zero int zero = 0; k = 911 / zero; break; case 1: // null pointer int[] b = null; k = b[0]; break; case 2: // array index out of bound int[] c = new int[2]; k = c[9]; break; case 3: // string index out of bound char ch = "abc".charat(99); break; catch (Exception e) System.out.println("\nTest case #" + i + "\n");

38 Java System.out.println(e); 3.10 3.10 3.11 Java Windows 1 Windows 2 Java Java Java Java

3 Java 39 Macintosh MS-DOS Java Java Java Java Thread.currentThread class Deposit static int balance = 1000; // simulate the balance kept remotely public static void main(string[] args) Account account = new Account(); DepositThread first, second; first = new DepositThread(account, 1000, "#1"); second = new DepositThread(account, 1000, "\t\t\t\t#2"); // start the transactions first.start(); second.start(); // wait for both transactions to finish try first.join(); second.join(); catch (InterruptedException e) // print out the final balance System.out.println("*** Final balance is " + balance); class Account

40 Java void deposit(int amount, String name) int balance; System.out.println(name + " trying to deposit " + amount); System.out.println(name + " getting balance..."); balance = getbalance(); System.out.println(name + " balance got is " + balance); balance += amount; System.out.println(name + " setting balance..."); setbalance(balance); System.out.println(name + " new balance set to " + Deposit.balance); int getbalance() try // simulate the delay in getting balance remotely Thread.sleep(5000); catch (InterruptedException e) return Deposit.balance; void setbalance(int balance) try // simulate the delay in setting new balance remotely Thread.sleep(5000); catch (InterruptedException e) Deposit.balance = balance; class DepositThread extends Thread Account account; int deposit_amount; String message; DepositThread(Account account, int amount, String message) this.message = message; this.account = account; this.deposit_amount = amount;

3 Java 41 public void run() account.deposit(deposit_amount, message); : Thread DepositThread run, run Account deposit sleep 3.11~ 3.13 3.11 3.12

42 Java 3.13 Java Java Java Java 3.12 1 Main public static 2 Java syncronize 3 4 Java C++ C++ 1998 Java 5 Java Java Java, _,$,,

4 4.1 4.1.1 30 IBM E.F.Codd SQL Server IBM DB2 ORACLE SYBASE Informix 4.1.2 E.F.Codd 1976 6 table 1.1 E.F.Codd E.F.Codd

44 Java 4.1.3 RDBMS RDBMS DB MS R DBMS Web company ad hit company hit Pickles 7 14 (1) company Pickles, Inc 14 (2) ad 48 101 (3) ad hit 48 101 C.J.Date E.F.Codd 1 key

4 45 primary key PK NULL foreign key FK R S KS common key S parent table R child table S R 1:N (1) (2) (3) F K P K 2 3 4.1.4 SQL SQL

46 Java 20 70 IBM SQL Server 7 SQL ANSI-92 SQL SQL Server 7 SQL Server 7 SQL SQL Transact-SQL SQL Server 7 4.2 SQL SQL SQL JDBC SQL SQL JDBC SQL sequel S Q L SQL sequel 4.2.1 SQL SQL 1974 Boyce Chamberlin SEQUEL 1976 IBM San Jose System R SEQUEL2 SQL 1986 ANSI SQL SQL SQL SQL SQL Server 7.0 pubs 4.2.2 SQL SQL Server SQL SELECT FROM WHERE SELECT < > FROM < > WHERE < >

4 47 SELECT FROM WHERE SQL SELECT SQL SELECT ANSI SQL SELECT select_list [ INTO new_table_] FROM table_source [WHERE search_condition] [GROUP BY group_by_expression] [ HAVING search_condition] [ORDER BY order_expression [ASC DESC] ] 1 SELECT * FROM TABLE _ NAME SELECT* FROM AUTHORS 4.1 23 4.1 Select 2 SELECT COLUMN_NAME[,...n] FROM TABLE _ NAME

48 Java SELECT au_id,au_fname,au_lname FROM AUTHORS 4.2 ID 4.2 SELECT SELECT AU_FNAME,AU_LNAME,AU_ID FROM AUTHORS 3 SELECT COLUMN_NAME 'STRING LITERAL'[,...n] FROM TABLE _ NAME SELECT AU_FNAME,AU_LNAME,' ', A U _ I D FROM AUTHORS 4.3 Au_Id 4 SQL 1 = SELECT COLUMN_HEADING=COLUMN_NAME[... n ] FROM TABLE_NAME 2 SELECT COLUMN_NAME COLUMN_HEADING[... n ] FROM TABLE_NAME f i r s t n a m e l a

4 49 s t n a m e SELECT ' ' = AU_FNAME, ' ' = AU_LNAME, ' ' = AU_ID FROM AUTHORS 4.4 SQL 4.3 4.4 5 SQL 1 0 % SELECT (PRICE*1.1),TITLE FROM TITLES 4.5 10%

50 Java 4.5 6 SQL ASIN(float_expression) float_expression ACOS(float_expression) float_expression ATAN(float_expression) float_expression ATN2(float_expression) float_expression1,float_expression2 SIN(float_expression) float_expression COS(float_expression) float_expression TAN(float_expression) float_expression COT(float_expression) float_expression DEGREES(numeric_expression) RADIANS(numeric_expression) EXP((float_expression)) float_expression POWER(numeric_expression,y) numeric_expression y SORT(float_expression) float_expression SQUARE(float_expression) float_expression LOG(float_expression) float_expression LOG10(float_expression) float_expression 10 ABS(numeric_expression) numeric_expression CEILING(numeric_expression) numeric_expression FLOOR(numeric_expression) numeric_expression RAND([seed]) 0 1 seed PI() 3.1415926535897931

4 51 ROUND(numeric_expression,length[,function]) numeric_expression numeric_expression length numeric_expression tinyint smallint int length numeric_expression length numeric_expression function ROUND tinyint smallint int 0 ROUND SIGN(numeric_expression) numeric_expression 0 1 0 1 SELECT TITLE_ID,ROUND(PRICE*ROYALTY/100,0) FROM TITLES 4.6 DBMS SQL Server 4.6 Round 7 WHERE WHERE SELECT SELECT_LIST FROM TABLE_LIST WHERE SEARCH_CONDITIONS = > = = = BETWEEN NOT BETWEEN

52 Java IN NOT IN LIKE NOT LIKE IS NULL IS NOT NULL AND OR NOT NOT, 8000 SELECT au_lname,au_fname,phone FROM AUTHORS WHERE ZIP>'8000' 4.7 4.7 BETWEEN 1 / 1 / 1 9 9 1 1 2 / 3 1 / 1 9 9 1 SELECT TITLE,PUBDATE FROM TITLES WHERE PUBDATE BETWEEN '1/1/91' AND '12/31/91' 4.8 IN MOD_COOK TRAD_COOK SELECT TITLE,TYPE FROM TITLES WHERE TYPE IN ('MOD_COOK','TRAD_COOK') 4.9 LIKE BOOK SELECT * FROM STORES WHERE STOR_NAME LIKE BOOK % 4.10

4 53 4.8 4.9 IN IS NULL SELECT TITLE FROM TITLES WHERE PRICE IS NULL 4.11 WHERE 3 AND OR NOT T 0866 1 8 4.12

54 Java 4.10 Like 4.11 Is NUll DISTINCT SELECT DISTINCT CITY, STATE FROM AUTHORS 4.13 ORDER BY ORDER BY 4.14

4 55 4.12 4.13 Distinct ANSI SQL AVG COUNT MAX MIN SUM DBMS ANSI SQL

56 Java 4.14 Order By 1 select count(*) from titles ----------- 18 (1 row(s) affected) 2 SELECT AVG(PRICE) FROM TITLES --------------------- 14.7662 (1 row(s) affected) Warning: Null value eliminated from aggregate. 3 SELECT MAX (PRICE) FROM TITLES --------------------- 22.9500 (1 row(s) affected) Warning: Null value eliminated from aggregate. 4 SELECT SUM(PRICE) FROM TITLES --------------------- 236.2600

4 57 (1 row(s) affected) Warning: Null value eliminated from aggregate. GROUP BY HAVING GROUP BY HAVING SELECT COLUMN_NAME[ C O L U M N _ N A M E ] FROM TA B L E _ N A M E WHERE SEARCH_CONDITION [GROUP BY [ALL] AGGREGATE_FREE_EXPRESSION [ AGGREGATE_FREE_EXPRESSION ] ] [ HAVING SEARCH_CONDITIONS] 1 SELECT TITLE_ID,COPIES_SOLD=SUM(QTY) FROM SALES GROUP BY TITLE_ID 4.15 4.15 Group By GROUP BY GROUP BY HAVING 2 3 0 SELECT TITLE_ID,COPIES_SOLD=SUM(QTY) FROM SALES GROUP BY TITLE_ID HAVING SUM(QTY)>30 4.16

58 Java 4.16 Having 4.3 SQL SELECT COLUMN_NAME C O L U M N _ N A M E [,... n ] FROM TA B L E _ N A M E TA B L E _ N A M E [,... n ] WHERE TABLE_NAME.COLUMN_NAME JOIN_OPERATOR TABLE_NAME. C O L U M N _ N A M E J O I N _ O P E R ATO R = > < > = < =! = < >! >!< 1 SELECT P.PUB_NAME,T.TITLE FROM PUBLISHERS AS P,TITLES AS T 4.17 PUB_NAME PUBLISHERS 2

4 59 4.17 SELECT P.PUB_NAME,T.TITLE FROM TITLES AS T,PUBLISHERS AS P WHERE T.PUB_ID=T.PUB_ID 4.18 4.18 3

60 Java 3 SALES SELECT STOR_NAME, QTY, title FROM TITLES,STORES, SALES WHERE TITLES.TITLE_ID=SALES.TITLE_ID AND STORES. STOR_ID=SALES.STOR_ID 4.19 4.19 4 SELECT A.TITLE_ID, A.AU_ID,B.AU_ID FROM TITLEAUTHOR AS A,TITLEAUTHOR AS B WHERE A.TITLE_ID=B.TITLE_ID AND A.AU_ID=B. AU_ID 4.20 5 1 SELECT TITLES.TITLE_ID,TITLE,QTY FROM TITLES,SALES WHERE TITLES.TITLE_ID *= SALES.TITLE_ID

4 61 4.20 *= TITLE_ID QTY -------- ------ PC1035 30 PS1372 20 BU1111 25 PS7777 25 TC4203 20 PS2091 3 PS2091 75 PS2091 10 PS2091 20 PS2106 25 PC9999 NULL TC3218 40 PS3333 15 PC8888 50 MC2222 10 BU7832 15 TC7777 20 BU1032 5 BU1032 10 MC3021 25

62 Java MC3021 15 MC3026 NULL BU2075 35 (23 row(s) affected) 2 SELECT TITLES.TITLE_ID,QTY FROM TITLES,SALES WHERE TITLES.TITLE_ID = SALES.TITLE_ID TITLE_ID QTY -------- ------ BU1032 5 PS2091 3 PC8888 50 PS2091 75 PS2091 10 TC3218 40 TC4203 20 TC7777 20 PS2091 20 MC3021 25 PS1372 20 PS2106 25 PS3333 15 PS7777 25 BU7832 15 MC2222 10 BU2075 35 MC3021 15 BU1032 10 BU1111 25 PC1035 30 (21 row(s) affected) 4.4 SELECT SELECT SELECT SELECT

4 63 1 SELECT TITLE=TITLE_ID, QUANTITY=QTY, TOTAL=(SELECT SUM(QTY) FROM SALES), PERCENTAGE_OF_TOTAL =(QTY)/(SELECT SUM(QTY)FROM SALES)*100) FROM SALES CONVERT 0 TITLE QUANTITY TOTAL PERCENTAGE_OF_TOTAL ------ -------- ----------- ------------------- BU1032 5 493 1.0141987829614605 PS2091 3 493 0.6085192697768762 PC8888 50 493 10.141987829614605 PS2091 75 493 15.212981744421908 PS2091 10 493 2.028397565922921 TC3218 40 493 8.1135902636916839 TC4203 20 493 4.056795131845842 TC7777 20 493 4.056795131845842 PS2091 20 493 4.056795131845842 MC3021 25 493 5.0709939148073024 PS1372 20 493 4.056795131845842 PS2106 25 493 5.0709939148073024 PS3333 15 493 3.0425963488843815 PS7777 25 493 5.0709939148073024 BU7832 15 493 3.0425963488843815 MC2222 10 493 2.028397565922921 BU2075 35 493 7.0993914807302234 MC3021 15 493 3.0425963488843815 BU1032 10 493 2.028397565922921 BU1111 25 493 5.0709939148073024 PC1035 30 493 6.0851926977687629 (21 row(s) affected) 2 IN

64 Java SELECT title_id,type,price FROM TITLES WHERE TITLE_ID IN (SELECT TITLE_ID FROM SALES) title_id type price -------- ------------ --------------------- BU1032 business 19.9900 BU1111 business 11.9500 BU2075 business 2.9900 BU7832 business 19.9900 MC2222 mod_cook 19.9900 MC3021 mod_cook 2.9900 PC1035 popular_comp 22.9500 PC8888 popular_comp 20.0000 PS1372 psychology 21.5900 PS2091 psychology 10.9500 PS2106 psychology 7.0000 PS3333 psychology 19.9900 PS7777 psychology 7.9900 TC3218 trad_cook 20.9500 TC4203 trad_cook 11.9500 TC7777 trad_cook 14.9900 (16 row(s) affected) 3 WHERE SELECT I D SELECT TITLE_ID,AU_ID,ROYALTYPER FROM TITLEAUTHOR AS TA WHERE ROYALTYPER= (SELECT MAX (ROYALTYPER) FROM TITLEAUTHOR WHERE TITLE_ID=TA.TITLE_ID) TITLE_ID AU_ID ROYALTYPER -------- ----------- ----------- BU1032 409-56-7008 60 BU1111 724-80-9391 60 BU2075 213-46-8915 100 BU7832 274-80-9391 100 MC2222 712-45-1867 100 MC3021 722-51-5454 75 PC1035 238-95-7766 100 PC8888 427-17-2319 50

4 65 PC8888 846-92-7186 50 PC9999 486-29-1786 100 PS1372 756-30-7391 75 PS2091 899-46-2035 50 PS2091 998-72-3567 50 PS2106 998-72-3567 100 PS3333 172-32-1176 100 PS7777 486-29-1786 100 TC3218 807-91-6654 100 TC4203 648-92-1872 100 TC7777 672-71-3249 40 (19 row(s) affected) 4 EXISTS EXISTS ( ) SELECT TITLE_ID,PRICE FROM TITLES WHERE EXISTS (SELECT * FROM SALES WHERE TITLES.TITLE_ID =SALES.TITLE_ID) TITLE_ID PRICE -------- --------------------- BU1032 19.9900 BU1111 11.9500 BU2075 2.9900 BU7832 19.9900 MC2222 19.9900 MC3021 2.9900 PC1035 22.9500 PC8888 20.0000 PS1372 21.5900 PS2091 10.9500 PS2106 7.0000 PS3333 19.9900 PS7777 7.9900 TC3218 20.9500 TC4203 11.9500 TC7777 14.9900 (16 row(s) affected) EXISTS EXISTS TRUE SELECT

66 Java 5 SELECT INTO SQL Server # #PER SELECT TITLE_ID,PRICE INTO #PER FROM TITLES WHERE EXISTS (SELECT * FROM SALES WHERE TITLES.TITLE_ID =SALES.TITLE_ID) 4.21 4.21 Exists #PER SELECT TITLE_ID,PRICE FROM #PER TITLE_ID PRICE -------- --------------------- BU1032 19.9900 BU1111 11.9500 BU2075 2.9900 BU7832 19.9900 MC2222 19.9900 MC3021 2.9900 PC1035 22.9500 PC8888 20.0000 PS1372 21.5900

4 67 PS2091 10.9500 PS2106 7.0000 PS3333 19.9900 PS7777 7.9900 TC3218 20.9500 TC4203 11.9500 TC7777 14.9900 (16 row(s) affected) 4.5 SQL SQL 1 INSERT [INTO] table_name WITH ( <table_hint_limited> [...n]) view_name rowset_function_limited [(column_list)] VALUES ( DEFAULT NULL expression [,...n] ) derived_table execute_statement DEFAULT VALUES <table_hint_limited> ::= INDEX(index_val [,...n]) FASTFIRSTROW HOLDLOCK PAGLOCK READCOMMITTED REPEATABLEREAD

68 Java ROWLOCK SERIALIZABLE TABLOCK TABLOCKX (1) (2) NOT NULL (3) TE CREATE TABLE #TE (BOOK_NAME CHAR(10),PRICE INT) INSERT #TE VALUES ('NKBOOK',197) 4.22 4.22 2 INSERT TABLE_NAME SELECT COLUMN_LIST FROM TABLE_LIST WHERE SEARCH_CONDITIONS

4 69 TE INSERT #TE SELECT TITLE_ID,PRICE FROM TITLES (18 row(s) affected) TE SELECT * FROM #TE BOOK_NAME PRICE ---------- ----------- NKBOOK 197 BU1032 20 BU1111 12 BU2075 3 BU7832 20 MC2222 20 MC3021 3 MC3026 NULL PC1035 23 PC8888 20 PC9999 NULL PS1372 22 PS2091 11 PS2106 7 PS3333 20 PS7777 8 TC3218 21 TC4203 12 TC7777 15 (19 row(s) affected) INSERT SELECT 3 ANSI SQL UPDATE UPDATE table_name WITH ( <table_hint_limited> [...n]) view_name rowset_function_limited

70 Java SET column_name = expression DEFAULT NULL @variable = expression @variable = column = expression [,...n] [FROM <table_source> [,...n] ] [WHERE <search_condition>] [WHERE CURRENT OF [GLOBAL] cursor_name cursor_variable_name ] [OPTION (<query_hint> [,...n] )] <table_source> ::= table_name [ [AS] table_alias ] [ WITH ( <table_hint> [,...n]) ] view_name [ [AS] table_alias ] rowset_function [ [AS] table_alias ] derived_table [AS] table_alias [ (column_alias [,...n] ) ] <joined_table> <joined_table> ::= <table_source> <join_type> <table_source> ON <search_condition> <table_source> CROSS JOIN <table_source> <joined_table> <join_type> ::= [ INNER LEFT RIGHT FULL [OUTER] ] [ <join_hint> ] JOIN <table_hint_limited> ::= INDEX(index_val [,...n]) FASTFIRSTROW HOLDLOCK PAGLOCK READCOMMITTED REPEATABLEREAD ROWLOCK

4 71 SERIALIZABLE TABLOCK TABLOCKX <table_hint> ::= INDEX(index_val [,...n]) FASTFIRSTROW HOLDLOCK NOLOCK PAGLOCK READCOMMITTED READPAST READUNCOMMITTED REPEATABLEREAD ROWLOCK SERIALIZABLE TABLOCK TABLOCKX UPDLOCK <query_hint> ::= HASH ORDER GROUP CONCAT HASH MERGE UNION LOOP MERGE HASH JOIN FAST number_rows FORCE ORDER MAXDOP ROBUST PLAN KEEP PLAN TE 1 UPDATE #TE SET PRICE=PRICE + 1 (19 row(s) affected) TE SELECT * FROM #TE

72 Java BOOK_NAME PRICE ---------- ----------- NKBOOK 198 BU1032 21 BU1111 13 BU2075 4 BU7832 21 MC2222 21 MC3021 4 MC3026 NULL PC1035 24 PC8888 21 PC9999 NULL PS1372 23 PS2091 12 PS2106 8 PS3333 21 PS7777 9 TC3218 22 TC4203 13 TC7777 16 (19 row(s) affected) #TE TITLES UPDATE #TE SET PRICE =(SELECT PRICE FROM TITLES WHERE #TE.BOOK_NAME=TITLES.TITLE_ID) (19 row(s) affected) #TE SELECT * FROM #TE BOOK_NAME PRICE ---------- ----------- NKBOOK NULL BU1032 20 BU1111 12 BU2075 3

4 73 BU7832 20 MC2222 20 MC3021 3 MC3026 NULL PC1035 23 PC8888 20 PC9999 NULL PS1372 22 PS2091 11 PS2106 7 PS3333 20 PS7777 8 TC3218 21 TC4203 12 TC7777 15 (19 row(s) affected) TITLES 4 ANSI SQL DELETE [FROM ] table_name WITH ( <table_hint_limited> [...n]) view_name rowset_function_limited [ FROM <table_source> [,...n] ] [WHERE <search_condition> [ CURRENT OF [ GLOBAL ] cursor_name cursor_variable_name ] ]

74 Java [OPTION (<query_hint> [,...n])] <table_source> ::= table_name [ [AS] table_alias ] [ WITH ( <table_hint> [,...n]) ] view_name [ [AS] table_alias ] rowset_function [ [AS] table_alias ] derived_table [AS] table_alias [ (column_alias [,...n] ) ] <joined_table> <joined_table> ::= <table_source> <join_type> <table_source> ON <search_condition> <table_source> CROSS JOIN <table_source> <joined_table> <join_type> ::= [ INNER LEFT RIGHT FULL [OUTER] ] [ <join_hint> ] JOIN <table_hint_limited> ::= INDEX(index_val [,...n]) FASTFIRSTROW HOLDLOCK PAGLOCK READCOMMITTED REPEATABLEREAD ROWLOCK SERIALIZABLE TABLOCK TABLOCKX <table_hint> ::= INDEX(index_val [,...n]) FASTFIRSTROW HOLDLOCK NOLOCK PAGLOCK READCOMMITTED READPAST

4 75 READUNCOMMITTED REPEATABLEREAD ROWLOCK SERIALIZABLE TABLOCK TABLOCKX UPDLOCK <query_hint> ::= HASH ORDER GROUP CONCAT HASH MERGE UNION FAST number_rows FORCE ORDER MAXDOP ROBUST PLAN KEEP PLAN #PER 10 DELETE #PER WHERE PRICE<10 (4 row(s) affected) #PER SELECT * FROM #PER TITLE_ID PRICE -------- --------------------- BU1032 19.9900 BU1111 11.9500 BU7832 19.9900 MC2222 19.9900 PC1035 22.9500 PC8888 20.0000 PS1372 21.5900 PS2091 10.9500 PS3333 19.9900 TC3218 20.9500 TC4203 11.9500

76 Java TC7777 14.9900 (12 row(s) affected) TITLES BUSINESS #TE DELETE #TE FROM #TE INNER JOIN TITLES ON #TE.BOOK_NAME=TITLES.TITLE_ID WHERE( TITLES.TYPE='BUSINESS') 4.23 4.23 #TE SELECT * FROM #TE BOOK_NAME PRICE ---------- ----------- NKBOOK NULL MC2222 20 MC3021 3 MC3026 NULL PC1035 23 PC8888 20 PC9999 NULL PS1372 22 PS2091 11 PS2106 7 PS3333 20 PS7777 8 TC3218 21

4 77 TC4203 12 TC7777 15 (15 row(s) affected) INNER JOIN *= 4.6 SQL (1) (2) (3) (4) 1 ANSI SQL CREATE PROC[EDURE] procedure_name [;number] [ @parameter data_type [VARYING] [= default] [OUTPUT] ] [,...n] [WITH RECOMPILE ENCRYPTION RECOMPILE, ENCRYPTION ] [FOR REPLICATION] AS sql_statement [...n] SQL

78 Java #TITLES CREATE PROCEDURE US_TITLES AS SELECT * FROM TITLES GO 4.24 4.24 EXEC EXECUTE US_TITLES 4.25 2 TITLES #TE IF OBJECT_ID('US_COM') IS NOT NULL DROP PROCEDURE US_COM GO CREATE PROCEDURE US_COM @PRICE INT AS IF @PRICE=0 BEGIN PRINT " " RETURN END

4 79 4.25 BEGIN TRANSACTION INSERT #TE SELECT TITLE_ID,PRICE FROM TITLES WHERE TITLES.PRICE<@PRICE COMMIT PRINT " " GO 4.26 EXEC US_COM 18 TITLES 18 #TE 4.26

80 Java BOOK_NAME PRICE -------------------- ----------- BU1111 12 BU2075 3 MC3021 3 PS2091 11 PS2106 7 PS7777 8 TC4203 12 TC7777 15 (8 row(s) affected) 3 OUTPUT CREATE PROCEDURE US_BOOL @PAR1 INT,@PAR2 INT,@PAR3 INT OUTPUT AS SELECT @PAR3=@PAR1*@PAR2 GO The command(s) completed successfully. DECLARE @P INT EXEC US_BOOL 10,10,@P OUTPUT PRINT @P GO 4.27 4 DROP PROCEDURE US_BOOL DROP PROCEDURE US_BOOL The command(s) completed successfully. US_BOOL DECLARE @P INT EXEC US_BOOL 10,10,@P OUTPUT PRINT @P GO

4 81 4.27 Server: Msg 2812, Level 16, State 62, Line -2123897080 Could not find stored procedure 'US_BOOL'. 4.7 1 2 3 4 10 10

5 JDBC 5.1 JDBC JDBC SQL Java API JDBC JDBC Java (Java Database Connectivity) Java JDBC / API Java API JDBC SQL JDBC API Sybase Oracle Informix JDBC API SQL Java Java JDBC Java Java JDBC JDBC Java Java JDBC API applet applet JDBC Intranet Windows Macintosh UNIX Java Java MIS Java JDBC Java JDBC JDBC (1) (2) SQL (3) Connection con = DriverManager.getConnection ( "jdbc:odbc:wombat", "login", "password"); Statement stmt = con.createstatement();

5 JDBC 83 ResultSet rs = stmt.executequery("select a, b, c FROM Table1"); while (rs.next()) int x = rs.getint("a"); String s = rs.getstring("b"); float f = rs.getfloat("c"); JDBC API JDBC SQL API API API JDBC JDBC API (1) Java SQL DBMS SQL JDBC SQL String Java SQL SQL Java SQL Java SQL SQL JDBC Java/SQL Java (2) Java JavaSoft API / Java SQL Java JDBC JDBC SQL 5.2 Java JDBC API Java applet JDBC SQL / Intranet Internet SQL SQL MIS API C C++ Java Java

84 Java Java JDBC Java 5.3 SQL (SQL) DBMS SQL SQL SQL JDBC API SQL JDBC API DBMS SQL DBMS SQL DBMS SQL JDBC SQL ODBC SQL JDBC JDBC SQL DatabaseMetaData DBMS DBMS JDBC API API API JDBC TM JDBC ANSI SQL-2 Entry Level ANSI SQL-2 1992 Entry Level SQL JDBC API JDBC TM JDBC JavaSoft JDBC API SQL Entry Level JavaSoft JDBC Internet JDBC API JDBC Java 5.4 JDBC ODBC API Microsoft ODBC API Java ODBC JDBC JDBC-ODBC JDBC (1) ODBC Java C Java C (2) ODBC C API Java API Java ODBC void * JDBC

5 JDBC 85 ODBC Java (3) ODBC JDBC (4) Java JDBC Java API ODBC ODBC Java JDBC JDBC Java JDBC API SQL Java ODBC ODBC JDBC JDBC ODBC X/Open SQL CLI JDBC Java Microsoft ODBC API RDO ADO OLE DB JDBC ODBC ODBC ODBC ODBC JDBC / SQL API 5.5 JDBC JDBC URL http://java.sun.com/products/jdbc 1 JavaSoft JavaSoft JDBC Java (JDK) JDBC JDBC JDBC-ODBC JDBC JDBC Java JDBC JDBC JDBC JDBC JDBC TM JDBC-ODBC ODBC JDBC JDBC DBMS DBMS JDBC 2 JDBC JDBC (1) JDBC-ODBC ODBC JavaSoft ODBC JDBC ODBC Java (2) API Java API

86 Java JDBC Oracle Sybase Informix DB2 DBMS (3) JDBC Java JDBC DBMS DBMS Java JDBC Intranet Internet Web JDBC (4) Java JDBC DBMS DBMS Intranet 3 4 JDBC 1 2 Java 1 2 3 4 Java JDBC applet 5.6 JDBC 1 Applet Java applet web applet JDBC applet applet applet internet applet Internet applet Internet applet applet (1) applet (2) Internet applet (3) Internet applet 2 Application Java Java Java Java Java Intranet Intranet

5 JDBC 87 Java GUI Java Java Intranet applet Customers Personnel DBMS JDBC driver Java 3 Servlet SUN Web 4 (1) applet Trusted applets Java applet applet appliction applet (2) Java GUI / DBMS Java RPC (remote procedure call) ORB (object request broker ) MIS C C++ Java Java Java 5.7 JDBC Java JDBC Java applications Java trusted Java applet 1 JDBC applet JDBC Java JDBC applets JDBC applets JDBC DriverManager JDBC Driver applet JDBC applet IP applet

88 Java 2 JDBC Java Java Java applet JDBC applet sun.sql.driver 3 Driver JDBC driver applet applet Java applet TCP/IP JDBC TCP Java applet JDBC TCP Java JDBC TCP applet A foobah TCP applet B applet B foobah TCP JDBC SecurityManager security = System.getSecurityManager(); if (security!= null) security.checkconnect(hostname, portnumber); Security.checkConnect java.lang.security Exception 4 JDBC SecurityManager security = System.getSecurityManager(); if (security!= null) security.checkread(filename);

5 JDBC 89 Security.checkRead java.lang.securityexception 5 applet JDBC-ODBC ODBC applet applet JDBC SecurityManager security = System.getSecurityManager(); if (security!= null) security.checkwrite("foobaz"); 5.8 JDBC JDK JDBC JDK JDBC http://java.sun.com/products/jdk/currentrelease 5.9 1 ODBC JDBC ODBC Windows JDBC 2 JDBC IT JDBC JDBC 3 JDBC 4 JDBC MS ADO JDBC ADO JDBC

6 JDBC JDBC JDBC 6.1 SQL Server 7.0 Windows 98 ODBC (1) SQL Server 6.1 6.1 (2) 6.2 TEST LOCATION 6.3 (3) TEST NEW\TABLE 6.4 (4) USER (5) USER 6.5 (6) 32 6.6

6 JDBC 91 6.2 6.3 (7) 6.7 (8) SQL Server SQL Server 6.8 (9) SQL Server 6.9 (10) 6.10 (11) 6.11 6.12

92 Java 6.4 6.5 6.6 ODBC

6 JDBC 93 6.7 6.8 6.9

94 Java 6.10 6.11 6.12

6 JDBC 95 (12) 6.13 JDBC 6.13 6.2 JDBC 1. JDBC DriverManager import java.net.url; import java.sql.*; class Test public static void main(string args[]) String l="jdbc:odbc:test"; try try Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); catch(java.lang.classnotfoundexception e) System.err.print("ClassNotFoundException: ");

96 Java System.err.println(e.getMessage()); Connection con=drivermanager.getconnection(l,"nkwht",""); DatabaseMetaData dma=con.getmetadata(); System.out.println(" :" + dma.geturl()); System.out.println("Driver :"+ dma.getdrivername()); System.out.println("Version :" + dma.getdriverversion()); con.close(); catch(sqlexception ex) while(ex!=null) System.out.println(" "); System.out.println(ex.getSQLState()); System.out.println(ex.getMessage()); System.out.println(ex.getErrorCode()); ex=ex.getnextexception(); 6.14 6.14

6 JDBC 97 2. Class.forName sun.jdbc.odbc.jdbcodbcdriver Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); java.lang.system jdbc.drivers DriverManager DriverManager jdbc.drivers DriverManager ~/.hotjava/properties HotJava jdbc.drivers=foo.bah.driver:wombat.sql.driver:bad.test.ourdriver; DriverManager Class.forName DriverManager jdbc.drivers Driver DriverManager.registerDriver JDBC DriverManager 3. Driver DriverManager DriverManager.getConnection DriverManager JDBC URL JDBC-ODBC JDBC DriverManager URL DriverManager jdbc.drivers Driver.connect DriverManager.getConnection URL URL JDBC-ODBC Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // String url = "jdbc:odbc:test ;

98 Java DriverManager.getConnection(url, "userid", "passwd"); Connection DriverManager getconnection() Connection Connection con=drivermanager.getconnection(); 4. DriverManager.getConnection URL DriverManager JDBC URL DriverManager Driver getconnection URL Driver connect URL JDBC Driver DriverManager URL "jdbc:odbc:wombat" oboy 12Java String url = "jdbc:odbc:wombat"; Connection con = DriverManager.getConnection(url, "oboy", "12Java"); 5. URL URL URL JDBC URL URL Internet URL ftp http file Internet URL ftp://javasoft.com/docs/jdk-1_apidocs.zip http://java.sun.com/products/jdk/currentrelease file:/home/haroldw/docs/books/tutorial/summary.html URL file URL ftp http URL JavaSoft URL URL http://java.sun.com JDBC JDBC URL http://java.sun.com/products/jdbc 6. JDBC URL JDBC URL JDBC URL

6 JDBC 99 JDBC URL URL JDBC JDBC URL JDBC URL odbc URL JDBC URL applet JDBC URL JDBC URL JDBC DNS NIS DCE, JDBC URL jdbc:< >:< > JDBC URL Jdbc JDBC URL jdbc < > odbc ODBC URL JDBC-ODBC URL jdbc:odbc:test odbc TEST ODBC JDBC URL URL jdbc:dcenaming:accounts-payable URL DCE accounts-payable < > ODBC fred Internet JDBC URL URL // : / dbnet Internet JDBC URL jdbc:dbnet://wombat:356/test 7. ODBC odbc ODBC URL ODBC

100 Java jdbc:odbc:< >[;< >=< >]* jdbc:odbc jdbc:odbc:qeor7 jdbc:odbc:wombat jdbc:odbc:wombat;cachesize=20;extensioncase=lower jdbc:odbc:qeora;uid=kgh;pwd=fooey 8. TRY CATCH JDK 6.15 import java.net.url; import java.sql.*; class Test public static void main(string args[]) String l="jdbc:odbc:test"; Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con=drivermanager.getconnection(l,"nkwht",""); DatabaseMetaData dma=con.getmetadata(); System.out.println(" :" + dma.geturl()); System.out.println("Driver :"+ dma.getdrivername()); System.out.println("Version :" + dma.getdriverversion()); con.close(); 6.15

6 JDBC 101 6.3 1, TRY CATCH JDK 2 String l="jdbc:odbc:test"; Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con=drivermanager.getconnection(l,"nkwht",""); URL Connection 3 Connection void clearwarnings() void close() void commit() Statement createstatement() Statement createstatement(int resultsettype, int resultsetconcurrency) boolean getautocommit() String getcatalog() DatabaseMetaData getmetadata() int gettransactionisolation() Map gettypemap() SQLWarning getwarnings() boolean isclosed() boolean isreadonly() String nativesql(string sql) CallableStatement preparecall(string sql) CallableStatement preparecall(string sql, int resultsettype, int resultsetconcurrency) PreparedStatement preparestatement(string sql) PreparedStatement preparestatement(string sql, int resultsettype, int resultsetconcurrency) void rollback() void setautocommit(boolean autocommit) void setcatalog(string catalog) void setreadonly(boolean readonly) void settransactionisolation(int level) void settypemap(map map)

7 JDBC 7.1 JDBC SQL JDBC 7.1.1 import java.net.url; import java.sql.*; class Select public static void main(string args[]) String l="jdbc:odbc:test"; try try Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); catch(java.lang.classnotfoundexception e) System.err.print("ClassNotFoundException: "); System.err.println(e.getMessage()); Connection con=drivermanager.getconnection(l,"sa",""); Statement stmt = con.createstatement(); stmt.executeupdate( "INSERT INTO USERINFO " + "VALUES ('NKWHT',' ','2001-03-31 21:03')"); con.close();

7 JDBC 103 catch(sqlexception ex) while(ex!=null) System.out.println(" "); System.out.println(ex.getSQLState()); System.out.println(ex.getMessage()); System.out.println(ex.getErrorCode()); ex=ex.getnextexception(); SQL Server SQL : SELECT * FROM USERINFO 7.1 7.1 7.1.2 Class.forName Connection Statement Statement

104 Java executeupdate SQL Statement 7.1.3 Statement Statement SQL Statement SQL Statement PreparedStatement Statement CallableStatement PreparedStatement SQL Statement SQL PreparedStatement IN SQL CallableStatement Statement PreparedStatement IN CallableStatement OUT 1. Statement SQL Statement Connection createstatement Connection con = DriverManager.getConnection(url, "sunny", ""); Statement stmt = con.createstatement(); 2. Statement SQL Statement SQL Statement ResultSet rs = stmt.executequery("select a, b, c FROM Table2"); Statement SQL executequery executeupdate execute SQL executequery SELECT executeupdate INSERT UPDATE DELETE SQL DDL CREATE TABLE DROP TABLE INSERT UPDATE DELETE executeupdate CREATE TABLE DROP TABLE executeupdate execute Statement Statement ResultSet Statement PreparedStatement executequery executeupdate execute Statement SQL Statement.execute SQL PreparedStatement SQL SQL CallableStatement PreparedStatement PreparedStatement CallableStatement SQLException

7 JDBC 105 3. executequery ResultSet executeupdate execute DBMS commit Statement Java Statement DBMS 4. Statement SQL Statement SQL SQL DBMS keyword... parameters... (1) escape LIKE % _ SQL LIKE % _ \ escape 'escape-character' stmt.executequery("select name FROM Identifiers WHERE Id LIKE `\_%' escape `\'; (2) fn DBMS fn concat fn concat("hot", "Java"); fn user(); DBMS DatabaseMetaData getnumericfunctions getstringfunctions

106 Java (3) d t ts DBMS JDBC ISO DBMS JDBC SQL d `yyyy-mm-dd' yyyy mm dd DBMS '28- FEB-99' d 1999-02-28 TIME TIMESTAMP t `hh:mm:ss' ts `yyyy-mm-dd hh:mm:ss.f...' TIMESTAMP.f... call JDBC call procedure_name[(?,?,...)] call procedure_name[(?,?,...)] JDK CallableStatement DatabaseMetaData.supportsStoredProcedures (4) oj oj outer-join outer-join table LEFT OUTER JOIN table / outer-join ON search-condition SQL JDBC DatabaseMetaData supportsouterjoins supportsfullouterjoins supportslimitedouterjoins Statement.setEscapeProcessing setescapeprocessing PreparedStatement PreparedStatement 7.2 SQL Server PUBS

7 JDBC 107 PUB 7-2 7.2 SQL Server SQL Server DATABASE PUBS TABLES TITLE 7.3 7.3 PROPERTIES PUBLIC 7.4 2 JDBC

108 Java 7.4 Java import java.net.url; import java.sql.*; class Select public static void main(string args[]) String l="jdbc:odbc:pub"; try try Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); catch(java.lang.classnotfoundexception e) System.err.print("ClassNotFoundException: "); System.err.println(e.getMessage()); Connection con=drivermanager.getconnection(l,"sa",""); Statement stmt = con.createstatement(); ResultSet rs=stmt.executequery("select * from TITLES"); while(rs.next())

7 JDBC 109 for(int i=1;i<11;i++) System.out.println(" " + i + " " + rs.getstring(i)); con.close(); catch(sqlexception ex) while(ex!=null) System.out.println(" "); System.out.println(ex.getSQLState()); System.out.println(ex.getMessage()); System.out.println(ex.getErrorCode()); ex=ex.getnextexception(); : 1 BU1032 2 The Busy Executive's Database Guide 3 business 4 1389 5 19.9900 6 5000.0000 7 10 8 4095 9 An overview of available database systems withemphasis on common business applications. Illustrated. 10 1991-06-12 00:00:00.000 1 BU1111 2 Cooking with Computers: Surreptitious Balance Sheets 3 business 4 1389 5 11.9500 6 5000.0000 7 10 8 3876 9 Helpful hints on how to use yourelectronic resources to the best

110 Java advantage. 10 1991-06-09 00:00:00.000 1 BU2075 2 You Can Combat Computer Stress! 3 business 4 0736 5 2.9900 6 10125.0000 7 24 8 18722 9 The latest medical and psychological techniques for livingwith the electronic office. Easy-to-understand explanations. 10 1991-06-30 00:00:00.000 1 BU7832 2 Straight Talk About Computers 3 business 4 1389 5 19.9900 6 5000.0000 7 10 8 4095 9 Annotated analysis of what computers can do for you: a no-hype guide for the critical user. 10 1991-06-22 00:00:00.000 1 MC2222 2 Silicon Valley Gastronomic Treats 3 mod_cook 4 0877 5 19.9900 6.0000 7 12 8 2032 9 Favorite recipes for quick, easy, and elegant meals. 10 1991-06-09 00:00:00.000 1 MC3021 2 The Gourmet Microwave 3 mod_cook 4 0877 5 2.9900 6 15000.0000

7 JDBC 111 7 24 8 22246 9 Traditional French gourmet recipes adapted for modern microwave cooking. 10 1991-06-18 00:00:00.000 1 MC3026 2 The Psychology of Computer Cooking 3 UNDECIDED 4 0877 5 null 6 null 7 null 8 null 9 null 10 1998-11-13 03:10:53.657 1 PC1035 2 But Is It User Friendly? 3 popular_comp 4 1389 5 22.9500 6 7000.0000 7 16 8 8780 9 A survey of software for the naive user, focusing on the'friendliness' of each. 10 1991-06-30 00:00:00.000 1 PC8888 2 Secrets of Silicon Valley 3 popular_comp 4 1389 5 20.0000 6 8000.0000 7 10 8 4095 9 Muckraking reporting on the world's largest computerhardware and software manufacturers. 10 1994-06-12 00:00:00.000 1 PC9999 2 Net Etiquette 3 popular_comp

112 Java 4 1389 5 null 6 null 7 null 8 null 9 A must-read for computer conferencing. 10 1998-11-13 03:10:53.670 1 PS1372 2 Computer Phobic AND Non-Phobic Individuals: Behavior Variations 3 psychology 4 0877 5 21.5900 6 7000.0000 7 10 8 375 9 A must for the specialist,this book examines the difference between those who hate and fear computers and those who don't. 10 1991-10-21 00:00:00.000 1 PS2091 2 Is Anger the Enemy? 3 psychology 4 0736 5 10.9500 6 2275.0000 7 12 8 2045 9 Carefully researched study of the effects of strong emotions on the body. Metabolic charts included. 10 1991-06-15 00:00:00.000 1 PS2106 2 Life Without Fear 3 psychology 4 0736 5 7.0000 6 6000.0000 7 10 8 111 9 New exercise, meditation, and nutritional techniques that can reduce the shockof daily interactions. Popular audience. Sample menus included, exercise video

7 JDBC 113 available separately. 10 1991-10-05 00:00:00.000 1 PS3333 2 Prolonged Data Deprivation: Four Case Studies 3 psychology 4 0736 5 19.9900 6 2000.0000 7 10 8 4072 9 What happens when the data runs dry?searching evaluations of information-shortage effects. 10 1991-06-12 00:00:00.000 1 PS7777 2 Emotional Security: A New Algorithm 3 psychology 4 0736 5 7.9900 6 4000.0000 7 10 8 3336 9 Protecting yourself and your loved ones from undue emotional stress in the modern world. Use of computer and nutritional aids emphasized. 10 1991-06-12 00:00:00.000 1 TC3218 2 Onions, Leeks, and Garlic: Cooking Secrets of the Mediterranean 3 trad_cook 4 0877 5 20.9500 6 7000.0000 7 10 8 375 9 Profusely illustrated in color, this makes a wonderful gift book for a cuisine-oriented friend. 10 1991-10-21 00:00:00.000 1 TC4203 2 Fifty Years in Buckingham Palace Kitchens 3 trad_cook 4 0877 5 11.9500

114 Java 6 4000.0000 7 14 8 15096 9 More anecdotes from the Queen's favorite cook describing life among English royalty. Recipes, techniques, tender vignettes. 10 1991-06-12 00:00:00.000 1 TC7777 2 Sushi, Anyone? 3 trad_cook 4 0877 5 14.9900 6 8000.0000 7 10 8 4095 9 Detailed instructions on how to make authentic Japanese sushi in your spare time. 10 1991-06-12 00:00:00.000 3,, ResultSet JDBC getstring (1) (2) ResultSet 7.3 ResultSet 1 ResultSet SQL get get ResultSet.next ResultSet SELECT a, b, c FROM Table1 a b c -------- --------- -------- 12345 Cupertino CA 83472 Redmond WA

7 JDBC 115 83492 Boston MA SQL SQL 1 int 2 String 3 java.sql.statement stmt = conn.createstatement(); ResultSet r = stmt.executequery("select a, b, c FROM Table1"); while (r.next()) // int i = r.getint("a"); String s = r.getstring("b"); float f = r.getfloat("c"); System.out.println("ROW = " + i + " " + s + " " + f); 2 ResultSet next next next ResultSet ResultSet Statement SQL getcursorname DBMS DatabaseMetaData.supportsPositionedDelete supportspositionedupdate DBMS/ 3 getxxx ResultSet rs title String s = rs.getstring("title"); String s = rs.getstring(2); 1 getxxx getxxx select select * from table1 SQL getxxx getxxx

116 Java ResultSet ResultSet.getMetaData ResultSetMetaData ResultSet findcolumn 4 getxxx JDBC Java Java getxxx getstring VARCHAR JDBC VARCHAR Java String getstring Java String getxxx JDBC JDBC SQL x getxxx X getxxx getbytes getbinarystream getxxx LONGVARCHAR getasciistream getunicodestream getobject Java Object ResultSet.getXXX JDBC 7-1 ResultSet 7-1 ResultSet GetByte GetShort getint GetLong GetFloat GetDouble GetBigDecimal GetBoolean GetString getbytes GetDate GetTime GetTimestamp GetAsciiStream GetUnicodeStream getbinarystream UNICODE getobject 5 ResultSet LONGVARBINARY LONGVARCHAR

7 JDBC 117 getbytes getstring Statement.getMaxFieldSize ResultSet java.io.input ResultSet getxxx JDBC API getbinarystream getasciistream ASCII getunicodestream Unicode Java ASCII Unicode getasciistream java.sql.statement stmt = con.createstatement(); ResultSet r = stmt.executequery("select x FROM Table2"); // 4KB 1 byte buff = new byte[4096]; while (r.next()) Java.io.InputStream fin = r.getasciistream(1); for (;;) int size = fin.read(buff); if (size == -1) // break; // ASCII output.write(buff, 0, size); 6 NULL JDBC NULL ResultSet.wasNull JDBC NULL ResultSet.getXXX JDBC NULL wasnull Java null Java getxxx getstring getbigdecimal getbytes getdate gettime gettimestamp getasciistream getunicodestream getbinarystream getobject getbyte getshort getint getlong getfloat getdouble false getboolean 7 executequery ResultSet executeupdate SQL

118 Java / JDBC execute getresultset getupdatecount getmoreresults ResultSet ResultSet Statement ResultSet Statement 7.4 JDBC JDBC 1 SQL Server PUBS TITLES import java.net.url; import java.sql.*; class Delete public void main(string args[]) String l="jdbc:odbc:pub"; try try Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); catch(java.lang.classnotfoundexception e) System.err.print("ClassNotFoundException: "); System.err.println(e.getMessage()); Connection con=drivermanager.getconnection(l,"sa","");

7 JDBC 119 Statement stmt = con.createstatement(); stmt.executeupdate("delete from TITLES where price=18"); ResultSet rs=stmt.executequery("select * from TITLES"); while(rs.next()) for(int i=1;i<11;i++) System.out.println(" " + i + " " + rs.getstring(i)); con.close(); catch(sqlexception ex) while(ex!=null) System.out.println(" "); System.out.println(ex.getSQLState()); System.out.println(ex.getMessage()); System.out.println(ex.getErrorCode()); ex=ex.getnextexception(); 18 1 BU1032 2 The Busy Executive's Database Guide 3 business 4 1389 5 19.9900 6 5000.0000 7 10 8 4095 9 An overview of available database systems with emphasis on common business applications. Illustrated. 10 1991-06-12 00:00:00.000 1 BU1111 2 Cooking with Computers: Surreptitious Balance Sheets 3 business 4 1389 5 11.9500

120 Java 6 5000.0000 7 10 8 3876 9 Helpful hints on how to use your electronic resources to the best advantage. 10 1991-06-09 00:00:00.000 1 BU2075 2 You Can Combat Computer Stress! 3 business 4 0736 5 2.9900 6 10125.0000 7 24 8 18722 9 The latest medical and psychological techniques for living with the electronic office. Easy-to-understand explanations. 10 1991-06-30 00:00:00.000 1 BU7832 2 Straight Talk About Computers 3 business 4 1389 5 19.9900 6 5000.0000 7 10 8 4095 9 Annotated analysis of what computers can do for you: a no-hype guide for the critical user. 10 1991-06-22 00:00:00.000 1 MC2222 2 Silicon Valley Gastronomic Treats 3 mod_cook 4 0877 5 19.9900 6.0000 7 12 8 2032 9 Favorite recipes for quick, easy, and elegant meals. 10 1991-06-09 00:00:00.000 1 MC3021 2 The Gourmet Microwave

7 JDBC 121 3 mod_cook 4 0877 5 2.9900 6 15000.0000 7 24 8 22246 9 Traditional French gourmet recipes adapted for modern microwave cooking. 10 1991-06-18 00:00:00.000 1 MC3026 2 The Psychology of Computer Cooking 3 UNDECIDED 4 0877 5 null 6 null 7 null 8 null 9 null 10 1998-11-13 03:10:53.657 1 PC1035 2 But Is It User Friendly? 3 popular_comp 4 1389 5 22.9500 6 7000.0000 7 16 8 8780 9 A survey of software for the naive user, focusing on the 'friendliness' of each. 10 1991-06-30 00:00:00.000 1 PC8888 2 Secrets of Silicon Valley 3 popular_comp 4 1389 5 20.0000 6 8000.0000 7 10 8 4095 9 Muckraking reporting on the world's largest computer hardware and software manufacturers.

122 Java 10 1994-06-12 00:00:00.000 1 PC9999 2 Net Etiquette 3 popular_comp 4 1389 5 null 6 null 7 null 8 null 9 A must-read for computer conferencing. 10 1998-11-13 03:10:53.670 1 PS1372 2 Computer Phobic AND Non-Phobic Individuals: Behavior Variations 3 psychology 4 0877 5 21.5900 6 7000.0000 7 10 8 375 9 A must for the specialist,this book examines the difference between those who hate and fear computers and those who don't. 10 1991-10-21 00:00:00.000 1 PS2091 2 Is Anger the Enemy? 3 psychology 4 0736 5 10.9500 6 2275.0000 7 12 8 2045 9 Carefully researched study of the effects of strong emotions on the body. Metabolic charts included. 10 1991-06-15 00:00:00.000 1 PS2106 2 Life Without Fear 3 psychology 4 0736 5 7.0000 6 6000.0000

7 JDBC 123 7 10 8 111 9 New exercise, meditation, and nutritional techniques that can reduce the shock of daily interactions. Popular audience. Sample menus included, exercise video available. separately. 10 1991-10-05 00:00:00.000 1 PS3333 2 Prolonged Data Deprivation: Four Case Studies 3 psychology 4 0736 5 19.9900 6 2000.0000 7 10 8 4072 9 What happens when the data runs dry?searching evaluations of information-shortage effects. 10 1991-06-12 00:00:00.000 1 PS7777 2 Emotional Security: A New Algorithm 3 psychology 4 0736 5 7.9900 6 4000.0000 7 10 8 3336 9 Protecting yourself and your loved ones from undue emotional stress in the modern world. Use of computer and nutritional aids emphasized. 10 1991-06-12 00:00:00.000 1 TC3218 2 Onions, Leeks, and Garlic: Cooking Secrets of the Mediterranean 3 trad_cook 4 0877 5 20.9500 6 7000.0000 7 10 8 375 9 Profusely illustrated in color, this makes a wonderful gift book for a cuisine-oriented friend. 10 1991-10-21 00:00:00.000

124 Java 1 TC4203 2 Fifty Years in Buckingham Palace Kitchens 3 trad_cook 4 0877 5 11.9500 6 4000.0000 7 14 8 15096 9 More anecdotes from the Queen's favorite cook describing life among English royalty. Recipes, techniques, tender vignettes. 10 1991-06-12 00:00:00.000 1 TC7777 2 Sushi, Anyone? 3 trad_cook 4 0877 5 14.9900 6 8000.0000 7 10 8 4095 9 Detailed instructions on how to make authentic Japanese sushi in your spare time. 10 1991-06-12 00:00:00.000 2. Statement executeupdate (1) Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); (2) Connection con=drivermanager.getconnection(l,"sa",""); Connection (3) Statement stmt = con.createstatement(); Statement (4) stmt.executeupdate("delete from TITLES where price=18"); (5) ResultSet rs=stmt.executequery("select * from TITLES"); while(rs.next()) for(int i=1;i<11;i++) System.out.println(" " + i + " " + rs.getstring(i)); con.close();

7 JDBC 125 7.5 JDBC JDBC Statement 1 SQL Server PUBS TITLES import java.net.url; import java.sql.*; class Delete public void main(string args[]) String l="jdbc:odbc:pub"; try try Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); catch(java.lang.classnotfoundexception e) System.err.print("ClassNotFoundException: "); System.err.println(e.getMessage()); Connection con=drivermanager.getconnection(l,"sa",""); Statement stmt = con.createstatement(); stmt.executeupdate("update TITLES SET TYPE= BUSI_BOOK WHERE PRICE<18 AND PRICE > 12"); ResultSet rs=stmt.executequery("select * from TITLES"); while(rs.next()) for(int i=1;i<11;i++) System.out.println(" " + i + " " + rs.getstring(i));

126 Java con.close(); catch(sqlexception ex) while(ex!=null) System.out.println(" "); System.out.println(ex.getSQLState()); System.out.println(ex.getMessage()); System.out.println(ex.getErrorCode()); ex=ex.getnextexception(); 12~18 BUSI_BOOK 1 BU1032 2 The Busy Executive's Database Guide 3 business 4 1389 5 19.9900 6 5000.0000 7 10 8 4095 9 An overview of available database systems with emphasis on common business applications. Illustrated. 10 1991-06-12 00:00:00.000 1 BU1111 2 Cooking with Computers: Surreptitious Balance Sheets 3 business 4 1389 5 11.9500 6 5000.0000 7 10 8 3876 9 Helpful hints on how to use your electronic resources to the best advantage. 10 1991-06-09 00:00:00.000 1 BU2075

7 JDBC 127 2 You Can Combat Computer Stress! 3 business 4 0736 5 2.9900 6 10125.0000 7 24 8 18722 9 The latest medical and psychological techniques for living with the electronic office. Easy-to-understand explanations. 10 1991-06-30 00:00:00.000 1 BU7832 2 Straight Talk About Computers 3 business 4 1389 5 19.9900 6 5000.0000 7 10 8 4095 9 Annotated analysis of what computers can do for you: a no-hype guide for the critical user. 10 1991-06-22 00:00:00.000 1 MC2222 2 Silicon Valley Gastronomic Treats 3 mod_cook 4 0877 5 19.9900 6.0000 7 12 8 2032 9 Favorite recipes for quick, easy, and elegant meals. 10 1991-06-09 00:00:00.000 1 MC3021 2 The Gourmet Microwave 3 mod_cook 4 0877 5 2.9900 6 15000.0000 7 24 8 22246 9 Traditional French gourmet recipes adapted for modern microwave

128 Java cooking. 10 1991-06-18 00:00:00.000 1 MC3026 2 The Psychology of Computer Cooking 3 UNDECIDED 4 0877 5 null 6 null 7 null 8 null 9 null 10 1998-11-13 03:10:53.657 1 PC1035 2 But Is It User Friendly? 3 popular_comp 4 1389 5 22.9500 6 7000.0000 7 16 8 8780 9 A survey of software for the naive user, focusing on the 'friendliness' of each. 10 1991-06-30 00:00:00.000 1 PC8888 2 Secrets of Silicon Valley 3 popular_comp 4 1389 5 20.0000 6 8000.0000 7 10 8 4095 9 Muckraking reporting on the world's largest computer hardware and software manufacturers. 10 1994-06-12 00:00:00.000 1 PC9999 2 Net Etiquette 3 popular_comp 4 1389 5 null 6 null

7 JDBC 129 7 null 8 null 9 A must-read for computer conferencing. 10 1998-11-13 03:10:53.670 1 PS1372 2 Computer Phobic AND Non-Phobic Individuals: Behavior Variations 3 psychology 4 0877 5 21.5900 6 7000.0000 7 10 8 375 9 A must for the specialist,this book examines the difference between those who hate and fear computers and those who don't. 10 1991-10-21 00:00:00.000 1 PS2091 2 Is Anger the Enemy? 3 psychology 4 0736 5 10.9500 6 2275.0000 7 12 8 2045 9 Carefully researched study of the effects of strong emotions on the body. Metabolic charts included. 10 1991-06-15 00:00:00.000 1 PS2106 2 Life Without Fear 3 psychology 4 0736 5 7.0000 6 6000.0000 7 10 8 111 9 New exercise, meditation, and nutritional techniques that can reduce the shock of daily interactions. Popular audience. Sample menus included, exercise video available separately. 10 1991-10-05 00:00:00.000 1 PS3333

130 Java 2 Prolonged Data Deprivation: Four Case Studies 3 psychology 4 0736 5 19.9900 6 2000.0000 7 10 8 4072 9 What happens when the data runs dry? Searching evaluations of information-shortage effects. 10 1991-06-12 00:00:00.000 1 PS7777 2 Emotional Security: A New Algorithm 3 psychology 4 0736 5 7.9900 6 4000.0000 7 10 8 3336 9 Protecting yourself and your loved ones from undue emotional stress in the modern world. Use of computer and nutritional aids emphasized. 10 1991-06-12 00:00:00.000 1 TC3218 2 Onions, Leeks, and Garlic: Cooking Secrets of the Mediterranean 3 trad_cook 4 0877 5 20.9500 6 7000.0000 7 10 8 375 9 Profusely illustrated in color, this makes a wonderful gift book for a cuisine-oriented friend. 10 1991-10-21 00:00:00.000 1 TC4203 2 Fifty Years in Buckingham Palace Kitchens 3 trad_cook 4 0877 5 11.9500 6 4000.0000 7 14 8 15096

7 JDBC 131 9 More anecdotes from the Queen's favorite cook describing life among English royalty. Recipes, techniques, tender vignettes. 10 1991-06-12 00:00:00.000 1 TC7777 2 Sushi, Anyone? 3 busi_book 4 0877 5 14.9900 6 8000.0000 7 10 8 4095 9 Detailed instructions on how to make authentic Japanese sushi in your spare time. 10 1991-06-12 00:00:00.000 2. (1) Statement executeupdate (2) Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); (3) Connection con=drivermanager.getconnection(l,"sa",""); Connection (4) Statement stmt = con.createstatement(); Statement (5) stmt.executeupdate("update TITLES SET TYPE= BUSI_BOOK WHERE PRICE<18 AND PRICE > 12"); (6) ResultSet rs=stmt.executequery("select * from TITLES"); (7) while(rs.next()) for(int i=1;i<11;i++) System.out.println(" " + i + " " + rs.getstring(i)); (8) con.close(); 7.6 PreparedStatement 7.6.1 PreparedStatement PreparedStatement Statement PreparedStatement SQL

132 Java PreparedStatement SQL IN IN SQL IN setxxx PreparedStatement Statement SQL PreparedStatement Statement PreparedStatement Statement IN execute executequery executeupdate Statement SQL PreparedStatement 7.6.2 PreparedStatement PreparedStatement import java.net.url; import java.sql.*; class Prepared public static void main(string args[]) String l="jdbc:odbc:pub"; try try Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); catch(java.lang.classnotfoundexception e) System.err.print("ClassNotFoundException: "); System.err.println(e.getMessage()); Connection con=drivermanager.getconnection(l,"nkwht",""); Statement stmt = con.createstatement(); PreparedStatement sp=con.preparestatement("update titles set type='computer' where title_id=?"); sp.setstring(1,"bu1032"); sp.executeupdate(); ResultSet rs=stmt.executequery("select * from Titles"); while(rs.next())

7 JDBC 133 for(int i=1;i<4;i++) System.out.println(" " + i + " " + rs.getstring(i)); con.close(); catch(sqlexception ex) while(ex!=null) System.out.println(" "); System.out.println(ex.getSQLState()); System.out.println(ex.getMessage()); System.out.println(ex.getErrorCode()); ex=ex.getnextexception(); 1 BU1032 2 The Busy Executive's Database Guide 3 computer 4 1389 5 19.9900 6 5000.0000 7 10 8 4095 9 An overview of available database systems with emphasis on common business applications. Illustrated. 10 1991-06-12 00:00:00.000 1 BU1111 2 Cooking with Computers: Surreptitious Balance Sheets 3 business 4 1389 5 11.9500 6 5000.0000 7 10 8 3876

134 Java 9 Helpful hints on how to use your electronic resources to the best advantage. 10 1991-06-09 00:00:00.000 1 BU2075 2 You Can Combat Computer Stress! 3 business 4 0736 5 2.9900 6 10125.0000 7 24 8 18722 9 The latest medical and psychological techniques for living with the electronic office. Easy-to-understand explanations. 10 1991-06-30 00:00:00.000 1 BU7832 2 Straight Talk About Computers 3 business 4 1389 5 19.9900 6 5000.0000 7 10 8 4095 9 Annotated analysis of what computers can do for you: a no-hype guide for the critical user. 10 1991-06-22 00:00:00.000 1 MC2222 2 Silicon Valley Gastronomic Treats 3 mod_cook 4 0877 5 19.9900 6.0000 7 12 8 2032 9 Favorite recipes for quick, easy, and elegant meals. 10 1991-06-09 00:00:00.000 1 MC3021 2 The Gourmet Microwave 3 mod_cook 4 0877 5 2.9900

7 JDBC 135 6 15000.0000 7 24 8 22246 9 Traditional French gourmet recipes adapted for modern microwave cooking. 10 1991-06-18 00:00:00.000 1 MC3026 2 The Psychology of Computer Cooking 3 UNDECIDED 4 0877 5 null 6 null 7 null 8 null 9 null 10 1998-11-13 03:10:53.657 1 PC1035 2 But Is It User Friendly? 3 popular_comp 4 1389 5 22.9500 6 7000.0000 7 16 8 8780 9 A survey of software for the naive user, focusing on the 'friendliness' of each. 10 1991-06-30 00:00:00.000 1 PC8888 2 Secrets of Silicon Valley 3 popular_comp 4 1389 5 20.0000 6 8000.0000 7 10 8 4095 9 Muckraking reporting on the world's largest computer hardware and software manufacturers. 10 1994-06-12 00:00:00.000 1 PC9999 2 Net Etiquette

136 Java 3 popular_comp 4 1389 5 null 6 null 7 null 8 null 9 A must-read for computer conferencing. 10 1998-11-13 03:10:53.670 1 PS1372 2 Computer Phobic AND Non-Phobic Individuals: Behavior Variations 3 psychology 4 0877 5 21.5900 6 7000.0000 7 10 8 375 9 A must for the specialist,this book examines the difference between those who hate and fear computers and those who don't. 10 1991-10-21 00:00:00.000 1 PS2091 2 Is Anger the Enemy? 3 psychology 4 0736 5 10.9500 6 2275.0000 7 12 8 2045 9 Carefully researched study of the effects of strong emotions on the body. Metabolic charts included. 10 1991-06-15 00:00:00.000 1 PS2106 2 Life Without Fear 3 psychology 4 0736 5 7.0000 6 6000.0000 7 10 8 111 9 New exercise, meditation, and nutritional techniques that can

7 JDBC 137 reduce the shock of daily interactions. Popular audience. Sample menus included, exercise video available separately. 10 1991-10-05 00:00:00.000 1 PS3333 2 Prolonged Data Deprivation: Four Case Studies 3 psychology 4 0736 5 19.9900 6 2000.0000 7 10 8 4072 9 What happens when the data runs dry?searching evaluations of information-shortage effects. 10 1991-06-12 00:00:00.000 1 PS7777 2 Emotional Security: A New Algorithm 3 psychology 4 0736 5 7.9900 6 4000.0000 7 10 8 3336 9 Protecting yourself and your loved ones from undue emotional stress in the modern world. Use of computer and nutritional aids emphasized. 10 1991-06-12 00:00:00.000 1 TC3218 2 Onions, Leeks, and Garlic: Cooking Secrets of the Mediterranean 3 trad_cook 4 0877 5 20.9500 6 7000.0000 7 10 8 375 9 Profusely illustrated in color, this makes a wonderful gift book for a cuisine-oriented friend. 10 1991-10-21 00:00:00.000 1 TC4203 2 Fifty Years in Buckingham Palace Kitchens 3 trad_cook 4 0877

138 Java 5 11.9500 6 4000.0000 7 14 8 15096 9 More anecdotes from the Queen's favorite cook describing life among English royalty. Recipes, techniques, tender vignettes. 10 1991-06-12 00:00:00.000 1 TC7777 2 Sushi, Anyone? 3 busi_book 4 0877 5 14.9900 6 8000.0000 7 10 8 4095 9 Detailed instructions on how to make authentic Japanese sushi in your spare time. 10 1991-06-12 00:00:00.000 BU1032 computer preparedstatement 7.6.3 PreparedStatement 1 PreparedStatement con Connection IN SQL PreparedStatement PreparedStatement pstmt = con.preparestatement( "UPDATE table4 SET m =? WHERE x =?"); pstmt "UPDATE table4 SET m =? WHERE x =?" DBMS 2 IN PreparedStatement? setxxx XXX Java long setlong setxxx 123456789 100000000 pstmt.setlong(1, 123456789); pstmt.setlong(2, 100000000); clearparameters

7 JDBC 139 PreparedStatement PreparedStatement Statement pstmt PreparedStatement pstmt 10 pstmt Hi for 0 9 pstmt.setstring(1, "Hi"); for (int i = 0; i < 10; i++) pstmt.setint(2, i); int rowcount = pstmt.executeupdate(); 3 IN setxxx XXX Java JDBC SQL Java JDBC JDBC Guide 8.7.2 Java JDBC JDBC PreparedStatement pstmt 44 Java short pstmt.setshort(2, 44); 44 JDBC SMALLINT Java short IN Java JDBC JDBC JDBC SMALLINT setbyte JDBC TINYINT TINYINT SMALLINT JDBC Java JDBC SMALLINT setshort setbyte 4 setobject setobject JDBC JDBC Java Object JDBC JDBC Java Object JDBC setxxx Java JDBC setxxx Java JDBC setobject Java Object JDBC setobject Java setobject

140 Java Java JDBC 5. JDBC NULL IN setnull JDBC NULL IN JDBC Java null setxxx Java JDBC NULL JDBC setobject null 6. IN setbytes setstring IN Java JDBC JDBC IN setbinarystream setasciistream ASCII setunicodestream Unicode setxxx IN java.io.file file = new java.io.file("/tmp/data"); int filelength = file.length(); java.io.inputstream fin = new java.io.fileinputstream(file); java.sql.preparedstatement pstmt = con.preparestatement( "UPDATE Table5 SET stuff =? WHERE index = 4"); pstmt.setbinarystream (1, fin, filelength); pstmt.executeupdate(); fin 7.7 CallableStatement JDBC CallableStatement 7.7.1 CallableStatement CallableStatement DBMS CallableStatement (OUT) IN OUT INOUT JDBC

7 JDBC 141 call [(?,?,...)]? = call [(?,?,...)] call CallableStatement DBMS DatabaseMetaData DBMS supportsstoredprocedures true getprocedures CallableStatement Statement SQL PreparedStatement IN CallableStatement OUT INOUT OUT JDBC SQL JDBC NULL 7.7.2 CallableStatement import java.net.url; import java.sql.*; class Call public static void main(string args[]) String l="jdbc:odbc:pub"; try try Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); catch(java.lang.classnotfoundexception e) System.err.print("ClassNotFoundException: "); System.err.println(e.getMessage()); Connection con=drivermanager.getconnection(l,"nkwht",""); Statement stmt = con.createstatement(); CallableStatement cstmt=con.preparecall("call TITLE_SELECT(?)");

142 Java cs.setstring(1,"bu1032"); ResultSet rs=sp.executequery(); while(rs.next()) for(int i=1;i<4;i++) System.out.println(" " + i + " " + rs.getstring(i)); con.close(); catch(sqlexception ex) while(ex!=null) System.out.println(" "); System.out.println(ex.getSQLState()); System.out.println(ex.getMessage()); System.out.println(ex.getErrorCode()); ex=ex.getnextexception(); 1 BU1032 2 The Busy Executive's Database Guide 3 computer 4 1389 5 19.9900 6 5000.0000 7 10 8 4095 9 An overview of available database systems with emphasis on common business applications. Illustrated. 10 1991-06-12 00:00:00.000 7.7.3 CallableStatement CallableStatement

7 JDBC 143 CallableStatement Connection preparecall CallableStatement gettestdata CallableStatement cstmt = con.preparecall( "call gettestdata(?,?)");? IN OUT INOUT gettestdata 2 IN OUT IN CallableStatement setxxx PreparedStatement setxxx setfloat float OUT CallableStatement OUT JDBC DBMS JDBC JDBC registeroutparameter CallableStatement getxxx getxxx JDBC Java registeroutparameter JDBC JDBC getxxx Java OUT cstmt OUT getbyte OUT Java getbigdecimal OUT BigDecimal CallableStatement cstmt = con.preparecall( "call gettestdata(?,?)"); cstmt.registeroutparameter(1, java.sql.types.tinyint); cstmt.registeroutparameter(2, java.sql.types.decimal, 3); cstmt.executequery(); byte x = cstmt.getbyte(1); java.math.bigdecimal n = cstmt.getbigdecimal(2, 3); CallableStatement ResultSet OUT 3 INOUT INOUT registeroutparameter setxxx PreparedStatement setxxx registeroutparameter JDBC setxxx Java JDBC IN JDBC registeroutparameter JDBC getxxx Java byte setbyte registeroutparameter TINYINT JDBC getbyte

144 Java revisetotal INOUT setbyte 25 JDBC TINYINT registeroutparameter JDBC TINYINT JDBC TINYINT getbyte Java byte CallableStatement cstmt = con.preparecall( "call revisetotal(?)"); cstmt.setbyte(1, 25); cstmt.registeroutparameter(1, java.sql.types.tinyint); cstmt.executeupdate(); byte x = cstmt.getbyte(1); 4 OUT DBMS CallableStatement CallableStatement.getXXX OUT CallableStatement ResultSet execute OUT Statement getresultset getupdatecount getmoreresults CallableStatement.getXXX OUT 5 OUT NULL OUT JDBC NULL JDBC NULL getxxx null 0 false getxxx ResultSet 0 false JDBC NULL wasnull getxxx JDBC NULL true flase 5 ResultSet 7.8 1 2 PreparedStatement 3 PreparedStatement void addbatch() void clearparameters() boolean execute()

7 JDBC 145 ResultSet executequery() int executeupdate() ResultSetMetaData getmetadata() void setarray(int i, Array x) void setasciistream(int parameterindex, InputStream x, int length) void setbigdecimal(int parameterindex, BigDecimal x) void setbinarystream(int parameterindex, InputStream x, int length) void setblob(int i, Blob x) void setboolean(int parameterindex, boolean x) void setbyte(int parameterindex, byte x) void setbytes(int parameterindex, byte[] x) void setcharacterstream(int parameterindex, Reader reader, int length) void setclob(int i, Clob x) void setdate(int parameterindex, Date x) void setdate(int parameterindex, Date x, Calendar cal) void setdouble(int parameterindex, double x) void setfloat(int parameterindex, float x) void setint(int parameterindex, int x) void setlong(int parameterindex, long x) void setnull(int parameterindex, int sqltype) void setnull(int paramindex, int sqltype, String typename) void setobject(int parameterindex, Object x) void setobject(int parameterindex, Object x, int targetsqltype) void setobject(int parameterindex, Object x, int targetsqltype, int scale) void setref(int i, Ref x) void setshort(int parameterindex, short x) void setstring(int parameterindex, String x) void settime(int parameterindex, Time x) void settime(int parameterindex, Time x, Calendar cal) void settimestamp(int parameterindex, Timestamp x) void settimestamp(int parameterindex, Timestamp x, Calendar cal) void setunicodestream(int parameterindex, InputStream x, int length)

8 JDBC JDBC 8.1 JDBC JDBC JDBC 1 import java.net.url; import java.sql.*; class CreateTable public static void main(string args[]) String l="jdbc:odbc:pub"; try try Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); catch(java.lang.classnotfoundexception e) System.err.print("ClassNotFoundException: "); System.err.println(e.getMessage()); Connection con=drivermanager.getconnection(l,"nkwht",""); String sql="create table MyTable(user_name char(20),user_age int,user_lobby char(30))"; Statement stmt = con.createstatement(); stmt.executeupdate(sql);

8 JDBC 147 con.close(); catch(sqlexception ex) while(ex!=null) System.out.println(" "); System.out.println(ex.getSQLState()); System.out.println(ex.getMessage()); System.out.println(ex.getErrorCode()); ex=ex.getnextexception(); SQL Server PUBS MyTable, 8.1 8.1 8.2 2 (1) Statement executeupdate (2) Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); (3) Connection con=drivermanager.getconnection(l,"sa",""); Connection

148 Java 8.2 (4) Statement stmt = con.createstatement(); Statement (5) stmt.executeupdate("create table MyTable(user_name char(20),user_age int, user_ lobby char(30))"); (6) con.close(); Statement executeupdate 8.2 JDBC JDBC 1 MyTable import java.net.url; import java.sql.*; class DropTable public static void main(string args[]) String l="jdbc:odbc:pub"; try try Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

8 JDBC 149 catch(java.lang.classnotfoundexception e) System.err.print("ClassNotFoundException: "); System.err.println(e.getMessage()); Connection con=drivermanager.getconnection(l,"nkwht",""); String sql="drop Table MyTable"; Statement stmt = con.createstatement(); stmt.executeupdate(sql); con.close(); catch(sqlexception ex) while(ex!=null) System.out.println(" "); System.out.println(ex.getSQLState()); System.out.println(ex.getMessage()); System.out.println(ex.getErrorCode()); ex=ex.getnextexception(); SQL Server PUBS My Table 8.3 8.3

150 Java My Table 2 stmt.executeupdate("drop Table MyTable ); 8.3 JDBC 8.3.1 1 import java.net.url; import java.sql.*; class CreateView public static void main(string args[]) String l="jdbc:odbc:pub"; try try Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); catch(java.lang.classnotfoundexception e) System.err.print("ClassNotFoundException: "); System.err.println(e.getMessage()); Connection con=drivermanager.getconnection(l,"nkwht",""); String sql="create view MyView as select title,type,price from titles"; Statement stmt = con.createstatement(); stmt.executeupdate(sql); ResultSet rs=stmt.executequery("select * from MyView"); while(rs.next())

8 JDBC 151 for(int i=1;i<4;i++) System.out.println(" " + i + " " + rs.getstring(i)); con.close(); catch(sqlexception ex) while(ex!=null) System.out.println(" "); System.out.println(ex.getSQLState()); System.out.println(ex.getMessage()); System.out.println(ex.getErrorCode()); ex=ex.getnextexception(); 1 The Busy Executive's Database Guide 2 business 3 19.9900 1 Cooking with Computers: Surreptitious Balance Sheets 2 business 3 11.9500 1 You Can Combat Computer Stress! 2 business 3 2.9900 1 Straight Talk About Computers 2 business 3 19.9900 1 Silicon Valley Gastronomic Treats 2 mod_cook 3 19.9900 1 The Gourmet Microwave 2 mod_cook 3 2.9900

152 Java 1 The Psychology of Computer Cooking 2 UNDECIDED 3 null 1 But Is It User Friendly? 2 popular_comp 3 22.9500 1 Secrets of Silicon Valley 2 popular_comp 3 20.0000 1 Net Etiquette 2 popular_comp 3 null 1 Computer Phobic AND Non-Phobic Individuals: Behavior Variations 2 psychology 3 21.5900 1 Is Anger the Enemy? 2 psychology 3 10.9500 1 Life Without Fear 2 psychology 3 7.0000 1 Prolonged Data Deprivation: Four Case Studies 2 psychology 3 19.9900 1 Emotional Security: A New Algorithm 2 psychology 3 7.9900 1 Onions, Leeks, and Garlic: Cooking Secrets of the Mediterranean 2 trad_cook 3 20.9500 1 Fifty Years in Buckingham Palace Kitchens 2 trad_cook 3 11.9500 1 Sushi, Anyone? 2 busi_book 3 14.9900 SQL Server PUBS 8.4

8 JDBC 153 8.4 2 stmt.executeupdate("create view MyView as select title,type,price from titles"); 8.3.2 import java.net.url; import java.sql.*; class DropView public static void main(string args[]) String l="jdbc:odbc:pub"; try try Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); catch(java.lang.classnotfoundexception e)

154 Java System.err.print("ClassNotFoundException: "); System.err.println(e.getMessage()); Connection con=drivermanager.getconnection(l,"nkwht",""); String sql="drop View MyView"; Statement stmt = con.createstatement(); stmt.executeupdate(sql); con.close(); catch(sqlexception ex) while(ex!=null) System.out.println(" "); System.out.println(ex.getSQLState()); System.out.println(ex.getMessage()); System.out.println(ex.getErrorCode()); ex=ex.getnextexception(); SQL Server PUBS MyView 8.5 8.5

8 JDBC 155 8.4 1 DBA 2 JDBC JDBC Connection 3

9 9.1 Servlet Servlets Java 2.0 Java Servlets / Java-enabled web,, servlet HTML servlet CGI WEB servlet CGI, CGI servlet Java servlet Servlet API, servlet, servlet CGI, servlet, servlets web Servlet CGI : Servlet Java Servlet API, a standard Java extension Java 9.2 Servlet servlet HTML HTTPS POSTed, servlet, servlet ; Servlet servlets servlet servlet,

9 157 9.3 Servlet servlet Java Java Servlet API Servlet interface servlets implement ( ) HttpServlet Servlet interface servlet Servlet servlet servlet, ServletRequest ServletResponse ServletRequest class, ServletResponse class servlet ServletRequest interface, servlet, ServletInputStream, HTTP POST PUT ServletRequest servlet : HttpServletRequest HTTP-specific ServletResponse interface servlet servlet mime,, ServletOutputStream, ServletResponse protocol-specific : HttpServletResponse servlet HTTP-specific classes interfaces Servlet HTTP servlets session-tracking capabilities servlet API servlet 9.4 Servlet servlets servlets servlets lifecycle servlet, servlet init servlet destroy servlet servlet, servlet service service :, Servlets service,, service thread-safe service servlet field, service SingleThreadModel interface interface threads Servlets servlet lifecycle, thread-safe servlet

158 Java 9.5 Servlet SUN JSWDK Serverlet Serverlet JSWDK 1 JDK Servlet Java_Home JDK ClassPath JSWDK JSWDK Serverlet.jar javax AutoExec.bat set classpath=c:\jdk1.3.0_01\serverlet set java_home=c:\jdk1.3.0_01 javax C:\jdk1.3.0_01\serverlet JDK C:\jdk1.3.0_01\ 2 C:\serverlet\jswdk-1.0.1 startserver.bat 9.1 9.1

9 159 9.2 9.3 stopserver.bat 9.4 9.2 9.3 9.4

160 Java 9.6 Servlet Servlet import java.io.*; import java.servlet.*; import javax.servlet.*; public class HelloWorld extends HttpServlet public void doget(httpservletrequest request, HttpServletResponse response) throws IOException, ServletException response.setcontenttype("text/html"); PrintWriter out = response.getwriter(); out.println("<html>"); out.println("<body>"); out.println("<head>"); out.println("<title>hello World!</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>hello World!</h1>"); out.println("</body>"); out.println("</html>"); 9.5 9.5 Hello World

9 161 import javax.servlet.*; Servlet Servlet HttpServlet GenericServerlet HTTP doget dopost HTTP get post HTTP 1.1 HTTP Service response.setcontenttype("text/html"); PrintWriter out = response.getwriter(); out.println("<html>"); out.println("<body>"); out.println("<head>"); out.println("<title>hello World!</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>hello World!</h1>"); out.println("</body>"); out.println("</html>"); HTML import java.io.*; import java.servlet.*; import javax.servlet.*; public class RequestInfo extends HttpServlet public void doget(httpservletrequest request, HttpServletResponse response) throws IOException, ServletException response.setcontenttype("text/html"); PrintWriter out = response.getwriter(); out.println("<html>"); out.println("<body>"); out.println("<head>"); out.println("<title>request Information Example</title>"); out.println("</head>"); out.println("<body>"); out.println("<h3>request Information Example</h3>"); out.println("method: " + request.getmethod()); out.println("request URI: " + request.getrequesturi()); out.println("protocol: " + request.getprotocol()); out.println("pathinfo: " + request.getpathinfo());

162 Java out.println("remote Address: " + request.getremoteaddr()); out.println("</body>"); out.println("</html>"); /** * We are going to perform the same operations for POST requests * as for GET methods, so this method just sends the request to * the doget method. */ public void dopost(httpservletrequest request, HttpServletResponse res) throws IOException, ServletException doget(request, response); 9.6 9.6 HttpServletRequest getmethod() getrequesturi() import java.io.*; import java.servlet.*; import javax.servlet.*; public class RequestHeaderExample extends HttpServlet

9 163 public void doget(httpservletrequest request, HttpServletResponse response) throws IOException, ServletException response.setcontenttype("text/html"); PrintWriter out = response.getwriter(); Enumeration e = req.getheadernames(); while (e.hasmoreelements()) String name = (String)e.nextElement(); String value = req.getheader(name); out.println(name + " = " + value); 9.7 9.7 Http 9.7 Servlet Servlet Servlet * Servlet

164 Java */ import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; /* WEB HTTP */ public class ReqInfoServlet extends HttpServlet /* req HttpServletRequest res HttpServletResponse */ public void service(httpservletrequest req, HttpServletResponse res) throws IOException ServletOutputStream os; Enumeration paramnames; String paramname, paramvalue; Enumeration hdrnames; String hdrdate, hdrname, hdrvalue; /* */ res.setcontenttype("text/plain"); PrintWriter pw = new PrintWriter(res.getOutputStream()); /* */ pw.println("request protocol is " + req.getprotocol()); pw.println("request scheme is " + req.getscheme()); /* */ pw.println("remote host is " + req.getremotehost()); pw.println("remote address is " + req.getremoteaddr()); /* */ pw.println("receiving server is " + req.getservername() + " on port number " + req.getserverport()); /* */ hdrnames = req.getheadernames(); /* Enumeration */ pw.println(); pw.println("header data is:");

9 165 while(hdrnames.hasmoreelements()) /* hdrname = (String)hdrNames.nextElement(); /* hdrvalue = (String)req.getHeader(hdrName); /* pw.println("name = " + hdrname + "; value = " + hdrvalue); pw.println(); paramnames = req.getparameternames(); /* Enumeration */ pw.println("request parameters are:"); while(paramnames.hasmoreelements()) paramname = (String)paramNames.nextElement(); paramvalue = (String)req.getParameter(paramName); pw.println("name = " + paramname + "; value = " + paramvalue); /* pw.flush(); pw.close(); // service() // Req Info Servlet 9.8 9.8

166 Java 9.8 1 Servlet Servlet Java 2 Servlet Servlet IT Servlet IT 3 Servlet HTTP HTTP Servlet 4 Servlet HttpServlet HttpServletRequest HttpServletResponse Servlet

10 Web Servlet Web Web Mail Servlet CGI CGI Servlet Servlet Web 10.1 Web HTML 1. <Form> </Form> <HR> FORM HTML FORM METHOD " " ACTION "URL " [ENCTYPE=" "] <INPUT TYPE=" " NAME=" "> /FORM ACTION URL URL HTTP METHOD HTTP GET POST GET GET URL POST ENCTYPE x www form encoded INPUT SELECT TEXTAREA HTML

168 Java 2. TEXTAREA SELECT INPUT INPUT TYPE FORM SUBMIT FROM TEXT RADIO Windows CHECKBOX PASSWORD HIDDEN IMAGE RESET TYPE INPUT HTML TYPE TYPE= text INPUT SELECT TEXTAREA NAME SELECTION <SELECT NAME " " > <OPTION> <OPTION> </SELECT> <HTML> <HEAD> <TITLE> </TITLE> </HEAD> <BODY > <PRE> <FORM METHOD=POST ACTION="http://202.113.0.3/main-bin/dumer/jiu_db" TARGET="_top"> <B> <B><INPUT NAME="mm" TYPE=text SIZE=8 > <B> </B><INPUT NAME="xm" TYPE=text SIZE=8 > <B> </B><INPUT NAME="sfz" TYPE=text SIZE=15> <B> </B><INPUT NAME="sr" TYPE=text SIZE=8 > <INPUT NAME="ok" TYPE=submit VALUE=" ">

10 Web 169 <INPUT NAME="cancel" TYPE=reset VALUE=" "> </FORM> </PRE> </BODY> </HTML> 10.1 10.1 1 <HTML> <HEAD> <TITLE>This is also a test!</title> </HEAD> <BODY > <INPUT TYPE=" text" NAME="wby" SIZE= 50 VALUE "1234510789"> </BODY> </HTML> TEXT INPUT SIZE MAXLENGTH MAXLENGTH VALUE IE 10.2

170 Java 10.2 2 TEXTAREA INPUT <HTML> <HEAD> <TITLE>This is also a test!</title> </HEAD> <BODY > <TEXTAREA NAME="dhwby" ROWS=10 COLS=50> </TEXTAREA> </BODY> </HTML> ROWS COLS <TEXTAREA> </TEXTAREA> TEXTAREA IE 10.3 3 <HTML> <HEAD> <TITLE>This is also a test!</title> </HEAD>

10 Web 171 10.3 <BODY > <INPUT TYPE="password" NAME="mm" SIZE=10 VALUE="1234510789"> </BODY> </HTML> TYPE="password" INPUT IE 10.4 10.4 4 INPUT TYPE " hidden"

172 Java <HTML> <HEAD> <TITLE>This is also a test!</title> </HEAD> <BODY > <INPUT TYPE= "hidden" NAME="state" VALUE=" state-information" > </BODY> </HTML> HTML hidden secret IE 10.5 10.5 5 <HTML> <HEAD> <TITLE>This is also a test!</title> </HEAD> <BODY >

10 Web 173 <INPUT TYPE="radio" NAME="dx" VALUE="a" CHECKED>a <INPUT TYPE= "radio" NAME="dx" VALUE="b">b <INPUT TYPE="radio" NAME="dx" VALUE="c" > c </BODY> </HTML> TYPE="radio" INPUT NAME VALUE CHECKED CHECKED CHECKED CHECKED IE 10.6 10.6 6 <HTML> <HEAD> <TITLE>This is also a test!</title> </HEAD> <BODY > <INPUT TYPE= "checkbox" NAME="fxk" VALUE=a CHECKED>a <INPUT TYPE="checkbox" NAME="fxk" VALUE b CHECKED > b

174 Java <INPUT TYPE="checkbox" NAME="fxk" VALUE=c>c <INPUT TYPE="checkbox" NAME="fxk" VALUE=d>d <INPUT TYPE="checkbox" NAME="fxk" VALUE=e >e </BODY> </HTML> TYPE="checkbox" INPUT VALUE CHECKBOX IE 10.7 10.7 7 <HTML> <HEAD> <TITLE>This is also a test!</title> </HEAD> <BODY> <SELECT NAME="xz" > <OPTION SELECTED>option 1 <OPTION>option 2 <OPTION>option 3 <OPTION>option 4 </SELECT> </BODY> </HTML>

10 Web 175 SELECT INPUT OPTION OPTION SELECT SELECT MULTIPLE OPTION SELECT OPTION VALUE IE 10.8 10.8 8 HIML <HTML> <HEAD> <TITLE>This is also a test!</title> </HEAD> <BODY> <INPUT TYPE="reset" VALUE = " " > </BODY> </HTML> TYPE="reset" INPUT VALUE reset NAME IE 10.9

176 Java 10.9 9. <HTML> <HEAD> <TITLE>This is also a test!</title> </HEAD> <BODY> <INPUT TYPE="submit" NAME="tj" VALUE=" "> </BODY> </HTML> TYPE="submit" INPUT VALUE submit NAME IE 10.10 10.10

10 Web 177 10.2 Servlet 1 Form Servlet import java.io.*; import java.servlet.*; import javax.servlet.*; public class RequestParamExample extends HttpServlet public void doget(httpservletrequest request, HttpServletResponse response) throws IOException, ServletException response.setcontenttype("text/html"); PrintWriter out = response.getwriter(); out.println("get Request. No Form Data Posted"); public void dopost(httpservletrequest request, HttpServletResponse res) throws IOException, ServletException Enumeration e = request.getparameternames(); PrintWriter out = res.getwriter (); while (e.hasmoreelements()) String name = (String)e.nextElement(); String value = request.getparamter(name); out.println(name + " = " + value); <html> <body> <head> <title>request Parameters Example</title> </head> <body bgcolor="white">

178 Java <a href="../servlets/reqparams.html"> <img src="../images/code.gif" height=24 width=24 align=right border=0 alt="view code"></a> <a href="../servlets/index.html"> <img src="../images/return.gif" height=24 width=24 align=right border=0 alt="return"></a> <h3>request Parameters Example</h3> Parameters in this request:<br> No Parameters, Please enter some <P> <form action="requestparamexample" method=post> First Name: <input type=text size=20 name=firstname> <br> Last Name: <input type=text size=20 name=lastname> <br> <input type=submit> </form> </body> </html> 10.11 10.12 10.11

10 Web 179 10.12 Servlet Enumeration e = request.getparameternames(); String name = (String)e.nextElement(); String value = request.getparamter(name); NextElement() getparameter HttpRequest 2 Cookie Cookie Servlet Cookie Cookie <html> <body bgcolor="white"> <head> <title>cookies Example</title> </head> <body> <a href="../servlets/cookies.html"> <img src="../images/code.gif" height=24 width=24 align=right border=0 alt="view code"></a> <a href="../servlets/index.html"> <img src="../images/return.gif" height=24 width=24 align=right border=0 alt="return"></a>

180 Java <h3>cookies Example</h3> Your browser isn't sending any cookies <P> Create a cookie to send to your browser<br> <form action="cookieexample" method=post> Name: <input type=text length=20 name=cookiename><br> Value: <input type=text length=20 name=cookievalue><br> <input type=submit></form> </body> </html> Servlet import java.io.*; import java.servlet.*; import javax.servlet.*; public class CookieExample extends HttpServlet public void doget(httpservletrequest request, HttpServletResponse response) throws IOException, ServletException response.setcontenttype("text/html"); PrintWriter out = response.getwriter(); // print out cookies Cookie[] cookies = request.getcookies(); for (int i = 0; i < cookies.length; i++) Cookie c = cookies[i]; String name = c.getname(); String value = c.getvalue(); out.println(name + " = " + value); // set a cookie String name = request.getparamter("cookiename"); if (name!= null && name.length() > 0) String value = req.getparameter("cookievalue"); Cookie c = new Cookie(name, value); res.addcookie(c);

10 Web 181 10.13 10.14 10.13 10.14 Servlet Cookie[] cookies = request.getcookies(); Cookies Cookie String name = c.getname(); String value = c.getvalue(); Cookie 3 Session Session Session

182 Java Session Session Session Session <html> <body bgcolor="white"> <head> <title>sessions Example</title> </head> <body> <a href="../servlets/sessions.html"> <img src="../images/code.gif" height=24 width=24 align=right border=0 alt="view code"></a> <a href="../servlets/index.html"> <img src="../images/return.gif" height=24 width=24 align=right border=0 alt="return"></a> <h3>sessions Example</h3> Session ID: To1010mC49021046416146796At <br> Created: Sat Mar 17 12:08:42 CST 2001<br> Last Accessed: Sat Mar 17 12:14:55 CST 2001 <P> The following data is in your session:<br> nkwht = 12511<br> <P> <form action="sessionexample" method=post> Name of Session Attribute: <input type=text size=20 name=dataname> <br> Value of Session Attribute: <input type=text size=20 name=datavalue> <br> <input type=submit> </form> </body> </html> </body> </html>

10 Web 183 Servlet import java.io.*; import java.servlet.*; import javax.servlet.*; public class SessionExample extends HttpServlet public void doget(httpservletrequest request, HttpServletResponse response) throws IOException, ServletException response.setcontenttype("text/html"); PrintWriter out = response.getwriter(); HttpSession session = request.getsession(true); // print session info Date created = new Date(session.getCreationTime()); Date accessed = new Date(session.getLastAccessedTime()); out.println("id " + session.getid()); out.println("created: " + created); out.println("last Accessed: " + accessed); // set session info if needed String dataname = request.getparameter("dataname"); if (dataname!= null && datename.length() > 0) String datavalue = request.getparameter("datavalue"); session.putvalue(dataname, datavalue); // print session contents String[] valuenames = session.getvaluenames(); if (valuenames!= null && valuenames.length > 0) for (int i = 0; i < valuenames.length; i++) String name = valuenames[i]; String value = session.getvalue(name).tostring(); out.println(name + " = " + value);

184 Java 10.15 10.16 10.15 10.16 Servlet 10.3 1

10 Web 185 String[] valuenames = session.getvaluenames(); if (valuenames!= null && valuenames.length > 0) for (int i = 0; i < valuenames.length; i++) String name = valuenames[i]; String value = session.getvalue(name).tostring(); out.println(name + " = " + value); 2 Session HttpSession session = request.getsession(true); // print session info Date created = new Date(session.getCreationTime()); Date accessed = new Date(session.getLastAccessedTime()); out.println("id " + session.getid()); out.println("created: " + created); out.println("last Accessed: " + accessed); 3 Cookie? Cookie

11 Web JDBC Servlet, Servlet JDBC CGI Servlet + JDBC Servlet 11.1 Servlet Servlet import java.io.*; import java.servlet.*; import javax.servlet.*; import java.net.url; import java.sql.*; public class LinkData extends HttpServerlet Connection con; public void init(serverletconfig conf) throws ServerletException super.init();// String l="jdbc:odbc:test"; try Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con=drivermanager.getconnection(l,"nkwht",""); catch(exception e) //

11 Web 187 public void doget(httpservletrequest request, HttpServletResponse response) throws IOException, ServletException response.setcontenttype("text/html"); PrintWriter out = response.getwriter(); out.println("<html>"); out.println("<body>"); out.println("<head>"); out.println("<title> Serverlet </title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>serverlet </h1>"); out.println("<pre>"); try DatabaseMetaData dma=con.getmetadata(); out.println(" :" + dma.geturl()); out.println("driver :"+ dma.getdrivername()); out.println("version :" + dma.getdriverversion()); out.println("</pre>"); con.close(); catch(sqlexception ex) while(ex!=null) out.println(" "); out.println(ex.getsqlstate()); out.println(ex.getmessage()); out.println(ex.geterrorcode()); ex=ex.getnextexception(); out.println("</body>"); out.println("</html>"); 11.1

188 Java 11.1 init Servlet 11.2 Servlet Servlet import java.io.*; import java.text.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import java.net.url; import java.sql.*; public class SelectData extends HttpServlet Connection con; public void init(servletconfig conf) throws ServletException

11 Web 189 super.init();// String l="jdbc:odbc:pub"; try Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con=drivermanager.getconnection(l,"sa",""); catch(exception e) // public void doget(httpservletrequest request, HttpServletResponse response) throws IOException, ServletException response.setcontenttype("text/html"); PrintWriter out = response.getwriter(); out.println("<html>"); out.println("<body>"); out.println("<head>"); out.println("<title> Serverlet </title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>serverlet </h1>"); out.println("<pre>"); try Statement stmt = con.createstatement(); ResultSet rs=stmt.executequery("select * from TITLES"); while(rs.next()) for(int i=1;i<11;i++) out.println(" " + i + " " + rs.getstring(i)); con.close(); out.println("</pre>"); con.close(); catch(sqlexception ex)

190 Java while(ex!=null) out.println(" "); out.println(ex.getsqlstate()); out.println(ex.getmessage()); out.println(ex.geterrorcode()); ex=ex.getnextexception(); out.println("</body>"); out.println("</html>"); 11.2 11.2 doget <pre> 11.3 Servlet import java.io.*; import java.text.*;

11 Web 191 import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import java.net.url; import java.sql.*; public class InsertData extends HttpServlet Connection con; public void init(servletconfig conf) throws ServletException super.init();// String l="jdbc:odbc:pub"; try Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con=drivermanager.getconnection(l,"sa",""); catch(exception e) // public void doget(httpservletrequest request, HttpServletResponse response) throws IOException, ServletException response.setcontenttype("text/html"); PrintWriter out = response.getwriter(); out.println("<html>"); out.println("<body>"); out.println("<head>"); out.println("<title> Serverlet </title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>serverlet </h1>"); out.println("<pre>"); try Statement stmt = con.createstatement(); String sql="insert MyTable values(' ',"; for(int i=0;i<=100;i++)

192 Java stmt.executeupdate(sql + i +")"); ResultSet rs=stmt.executequery("select * from MyTable"); while(rs.next()) for(int i=1;i<3;i++) out.println(" " + i + " " + rs.getstring(i)); con.close(); out.println("</pre>"); con.close(); catch(sqlexception ex) while(ex!=null) out.println(" "); out.println(ex.getsqlstate()); out.println(ex.getmessage()); out.println(ex.geterrorcode()); ex=ex.getnextexception(); out.println("</body>"); out.println("</html>"); 11.3

11 Web 193 100 Statement executepdate ResultSet 11.4 Servlet HTML Servlet HTML <html> <body> <head> <title> </title> </head> <body bgcolor="white"> <h1> </h1> <form action="deletedata" method=post> : <input type=text size=20 name=grade> <br> <input type=submit> </form> </body> </html> Servlet import java.io.*; import java.text.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import java.net.url; import java.sql.*; public class DeleteData extends HttpServlet Connection con; public void init(servletconfig conf) throws ServletException

194 Java super.init();// String l="jdbc:odbc:pub"; try Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con=drivermanager.getconnection(l,"sa",""); catch(exception e) // public void doget(httpservletrequest request, HttpServletResponse response) throws IOException, ServletException response.setcontenttype("text/html"); PrintWriter out = response.getwriter(); out.println("<html>"); out.println("<body>"); out.println("<head>"); out.println("<title> Serverlet </title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>serverlet </h1>"); out.println("<pre>"); String grade=request.getparameter("grade"); out.println("<h2> :" + grade + "</h2>"); try Statement stmt = con.createstatement(); String sql="delete from MyTable where grade=" + grade; stmt.executeupdate(sql); ResultSet rs=stmt.executequery("select * from MyTable"); while(rs.next()) for(int i=1;i<3;i++)

11 Web 195 out.println(" " + i + " " + rs.getstring(i)); con.close(); out.println("</pre>"); con.close(); catch(sqlexception ex) while(ex!=null) out.println(" "); out.println(ex.getsqlstate()); out.println(ex.getmessage()); out.println(ex.geterrorcode()); ex=ex.getnextexception(); out.println("</body>"); out.println("</html>"); 11.4 11.5 11.4

196 Java 11.5 11.5 Servlet Servlet HTML <html> <body> <head> <title> </title> </head> <body bgcolor="white"> <h1> </h1> <form action="http://localhost:8080/examples/servlet/updatedata" method=post> : <input type=text size=20 name=grade> <br> : <input type=text size=20 name=name> <br> <input type=submit> </form>

11 Web 197 </body> </html> Servlet import java.io.*; import java.text.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import java.net.url; import java.sql.*; public class UpdateData extends HttpServlet Connection con; public void init(servletconfig conf) throws ServletException super.init();// String l="jdbc:odbc:pub"; try Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con=drivermanager.getconnection(l,"sa",""); catch(exception e) // public void doget(httpservletrequest request, HttpServletResponse response) throws IOException, ServletException response.setcontenttype("text/html"); PrintWriter out = response.getwriter(); out.println("<html>"); out.println("<body>"); out.println("<head>"); out.println("<title> Serverlet </title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>serverlet </h1>");

198 Java out.println("<pre>"); String grade=request.getparameter("grade"); String name=request.getparameter("name"); try Statement stmt = con.createstatement(); String sql="update MyTable set name=" + name +"where grade=" + grade ; ResultSet rs=stmt.executequery("select * from MyTable"); while(rs.next()) for(int i=1;i<3;i++) out.println(" " + i + " " + rs.getstring(i)); con.close(); out.println("</pre>"); con.close(); catch(sqlexception ex) while(ex!=null) out.println(" "); out.println(ex.getsqlstate()); out.println(ex.getmessage()); out.println(ex.geterrorcode()); ex=ex.getnextexception(); out.println("</body>"); out.println("</html>"); 11.6 11.7 SQL Servlet /

11 Web 199 11.6 11.7 11.6 Servlet PreparedStatement PreparedStatement HTML <html> <body> <head>

200 Java <title>preparedstatement </title> </head> <body bgcolor="white"> <h1>preparedstatement </h1> <form action="http://localhost:8080/examples/servlet/predata" method=post> ID: <input type=text size=20 name=type_id> <br> : <input type=text size=20 name=type> <br> <input type=submit> </form> </body> </html> Servlet import java.io.*; import java.text.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import java.net.url; import java.sql.*; public class PreData extends HttpServlet Connection con; public void init(servletconfig conf) throws ServletException super.init();// String l="jdbc:odbc:pub"; try Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con=drivermanager.getconnection(l,"sa",""); catch(exception e) //

11 Web 201 public void doget(httpservletrequest request, HttpServletResponse response) throws IOException, ServletException response.setcontenttype("text/html"); PrintWriter out = response.getwriter(); out.println("<html>"); out.println("<body>"); out.println("<head>"); out.println("<title> Serverlet </title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>serverlet </h1>"); out.println("<pre>"); String type_id=request.getparameter("type_id"); try Statement stmt = con.createstatement(); PreparedStatement sp=con.preparestatement("update titles set type=? where title_id=?"); sp.setstring(1,type); sp.setstring(2,title); SP.executeUpdate(); ResultSet rs=stmt.executequery("select * from TITLES"); while(rs.next()) for(int i=1;i<3;i++) out.println(" " + i + " " + rs.getstring(i)); con.close(); out.println("</pre>"); con.close(); catch(sqlexception ex) while(ex!=null) out.println(" "); out.println(ex.getsqlstate()); out.println(ex.getmessage()); out.println(ex.geterrorcode());

202 Java ex=ex.getnextexception(); out.println("</body>"); out.println("</html>"); 11.8 11.9 11.8 11.9

11 Web 203 PreparedStatement Servlet 11.7 Servlet CallableStatement Servlet CallableStatement PUBS TITLES SQL Server SQL create procedure US_Serverlet @us_type char(20), @us_title_id char(20) as update titles set type=@us_type where title_id=@us_title_id 11.10 11.10 HTML <html> <body> <head> <title>callablestatement </title> </head> <body bgcolor="white"> <h1>callablestatement </h1>

204 Java <form action="http://localhost:8080/examples/servlet/predata" method=post> ID: <input type=text size=20 name=type_id> <br> : <input type=text size=20 name=type> <br> <input type=submit> </form> </body> </html> Servlet import java.io.*; import java.text.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import java.net.url; import java.sql.*; public class CallData extends HttpServlet Connection con; public void init(servletconfig conf) throws ServletException super.init();// String l="jdbc:odbc:pub"; try Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con=drivermanager.getconnection(l,"sa",""); catch(exception e) // public void doget(httpservletrequest request, HttpServletResponse response) throws IOException, ServletException response.setcontenttype("text/html");

11 Web 205 PrintWriter out = response.getwriter(); out.println("<html>"); out.println("<body>"); out.println("<head>"); out.println("<title> Serverlet </title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>serverlet </h1>"); out.println("<pre>"); String title_id=request.getparameter("type_id"); String type=request.getparameter("type"); try Statement stmt = con.createstatement(); CallableStatement cstmt=con.preparecall("call us_serverlet(?.?)"); cs.setstring(1,type); cs.setstring(2,title_id); cs.executeupdate(); ResultSet rs=stmt.executequery("select * from TITLES"); while(rs.next()) for(int i=1;i<10;i++) out.println(" " + i + " " + rs.getstring(i)); con.close(); out.println("</pre>"); con.close(); catch(sqlexception ex) while(ex!=null) out.println(" "); out.println(ex.getsqlstate()); out.println(ex.getmessage()); out.println(ex.geterrorcode()); ex=ex.getnextexception(); out.println("</body>");

206 Java out.println("</html>"); 11.11 11.12 11.11 11.12 11.8 1. Web Windows NT UNIX IBM WebSphere

11 Web 207 2 IBM DB2 ORACLE MS SQL Server 3 Servlet Servlet JSWDK Servlet \jswdk-1.0.1\examples\web-inf\ servlets 4 Web HTML Java HTML HTML MS Front Page Dream Waver

12 Servlet JDBC Servlet Servlet+JDBC Web Servlet+JDBC 12.1 1 SQL Server NEW DATABASE GUESTBOOK 12.1 12.1 GUESTBOOK 12.2 12.3

12 Servlet 209 12.2 12.3 GUESTBOOK 12.4~ 12.7 2 HTML JDBC+Servlet 12.4

210 Java 12.5 12.6 HTML <html> <head> <meta http-equiv="content-type" content="text/html; charset=gb2312"> <title> </title> <meta name="generator" content="microsoft FrontPage 3.0"> </head> <script language="vbscript"> sub ok()

12 Servlet 211 12.7 if(trim(document.forms(0).elements(0).value)<>"" trim(document.forms(0).elements(1).value)<>"" trim(document.forms(0).elements(2).value)<>"" instr(document.forms(0).elements(2).value,"<")=0) then document.forms(0).submit and and and else alert "!" document.forms(0).reset() end if end sub </script> <body text="#0000a0" bgcolor="#ffffff"> <div align="center"><center> <table width="75%" border="0"> <tr> <td width="27%"><img src="daxueshenghuo.jpg" width="156" height="60"> </td> <td width="73%"><img src="ad-baby.gif" width="468" height="60"></td> </tr> </table> <p> </p>

212 Java </center> </div> <p align="center"><font color="#ff00ff"><big><big> </big> </big> </font> </p> <p align="center"> <font color="#ff0000"> <small> HTML, </small></font> </p> <form method="post" action="liuyanban"> <div align="center"> <center><p> <input type="text" name="name" size="15"> E-MAIL<input type="text" name="mail" size="30"> </p> </center></div><div align="center"> <center><p> </p> </center></div> <div align="center"> <center><p> <textarea rows="5" name="main" cols="30"> </textarea> </p> </center> </div> <div align="center"> <center> <p> <input type="button" value=" " name="b1" onclick="ok()"> <input type="reset" value=" " name="b2"> <input type="button"

12 Servlet 213 value=" " name="b3" onclick="window.location.href='watch.asp'"> </p> </center></div> </form> </body> </html> 12.8 12.8 3 Servlet import java.io.*; import java.text.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import java.net.url; import java.sql.*; public class GuestBook extends HttpServlet Connection con;

214 Java public void init(servletconfig conf) throws ServletException super.init();// String l="jdbc:odbc:guestbook"; try Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con=drivermanager.getconnection(l,"sa",""); catch(exception e) // public void doget(httpservletrequest request, HttpServletResponse response) throws IOException, ServletException String name=request.getparameter("name"); String email=request.getparameter("email"); String content=request.getparameter("content"); java.util.date to_day = new java.util.date(); String date_string=to_day.tostring(); response.setcontenttype("text/html"); PrintWriter out = response.getwriter(); out.println("<html>"); out.println("<body>"); out.println("<head>"); if(name.length()==0 email.length()==0 content.length()==0 content.length()>500) // out.println("<title> </title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>,,!</h1>"); out.println("</body>"); out.println("</html>"); return ; try

12 Servlet 215 Statement stmt = con.createstatement(); String sql="insert GUESTBOOK values("+name+","+email+","+content+", "+date_string+")"; stmt.executeupdate(sql); con.close(); out.println("<title> </title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>!!</h1>"); catch(sqlexception ex) while(ex!=null) out.println(" "); out.println(ex.getsqlstate()); out.println(ex.getmessage()); out.println(ex.geterrorcode()); ex=ex.getnextexception(); out.println("</body>"); out.println("</html>"); import java.io.*; import java.text.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import java.net.url; import java.sql.*; public class WatchGuestBook extends HttpServlet Connection con; public void init(servletconfig conf) throws ServletException

216 Java super.init();// String l="jdbc:odbc:guestbook"; try Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con=drivermanager.getconnection(l,"sa",""); catch(exception e) // public void doget(httpservletrequest request, HttpServletResponse response) throws IOException, ServletException response.setcontenttype("text/html"); PrintWriter out = response.getwriter(); out.println("<html>"); out.println("<body>"); out.println("<head>"); out.println("<title> </title>"); out.println("</head>"); out.println("<body>"); out.println("<h1> </h1>"); out.println("<pre>"); try Statement stmt = con.createstatement(); ResultSet rs=stmt.executequery("select * from GuestBook"); while(rs.next()) out.println(" :") ; out.println(rs.getstring(1)); out.println(" :") ; out.println(rs.getstring(2)); out.println(" :") ; out.println(rs.getstring(3)); out.println(" :") ; out.println(rs.getstring(4));

12 Servlet 217 con.close(); out.println("</pre>"); con.close(); catch(sqlexception ex) while(ex!=null) out.println(" "); out.println(ex.getsqlstate()); out.println(ex.getmessage()); out.println(ex.geterrorcode()); ex=ex.getnextexception(); out.println("</body>"); out.println("</html>"); 12.9~ 12.11 12.9 4 HTML VBScript

218 Java 12.10 E-mail 12.11 <script language="vbscript"> sub ok() if(trim(document.forms(0).elements(0).value)<>"" trim(document.forms(0).elements(1).value)<>"" trim(document.forms(0).elements(2).value)<>"" instr(document.forms(0).elements(2).value,"<")=0) then document.forms(0).submit else and and and

12 Servlet 219 end if end sub alert "!" document.forms(0).reset() </script> 12.12 12.12 0 String email=request.getparameter("email"); String content=request.getparameter("content"); java.util.date to_day = new java.util.date(); String date_string=to_day.tostring(); response.setcontenttype("text/html"); PrintWriter out = response.getwriter(); out.println("<html>"); out.println("<body>"); out.println("<head>"); if(name.length()==0 email.length()==0 content.length()==0 content.length()>500) // out.println("<title> </title>"); out.println("</head>");

220 Java out.println("<body>"); out.println("<h1>,,!</h1>"); out.println("</body>"); out.println("</html>"); 12.2 1 SQL Server Count 12.13 12.13 Counter Vistit_time 12.14

12 Servlet 221 12.14 2 import java.io.*; import java.text.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import java.net.url; import java.sql.*; public class Counter extends HttpServlet Connection con; public void init(servletconfig conf) throws ServletException super.init();// String l="jdbc:odbc:guestbook"; try Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con=drivermanager.getconnection(l,"sa",""); catch(exception e) // public void doget(httpservletrequest request, HttpServletResponse response) throws IOException, ServletException java.util.date to_day = new java.util.date();

222 Java String date_string=to_day.tostring(); response.setcontenttype("text/html"); PrintWriter out = response.getwriter(); out.println("<html>"); out.println("<body>"); out.println("<head>"); try Statement stmt = con.createstatement(); ResultSet rs=stmt.executequery("select Counter from Count"); int Count=rs.getInt(1); Count++; stmt.executeupdate("update Count values('" + Interger.toString(Count,10) + "',"'" + date_string + "')"); con.close(); out.println("<title> </title>"); out.println("</head>"); out.println("<body>"); out.println("<h1> " + Interger.toString(Count,10) + "!!</h1>"); catch(sqlexception ex) while(ex!=null) out.println(" "); out.println(ex.getsqlstate()); out.println(ex.getmessage()); out.println(ex.geterrorcode()); ex=ex.getnextexception(); out.println("</body>"); out.println("</html>"); 12.15 3

12 Servlet 223 12.15 12.3 Servlet JDBC 1 2 zhuanzhi employer Zhuanzhi: Area

224 Java 3 HTML <html> <head> <meta http-equiv="content-language" content="en-us"> <meta http-equiv="content-type" content="text/html; charset=gb2312"> <meta name="generator" content="microsoft FrontPage 4.0"> <meta name="progid" content="frontpage.editor.document"> <title>new Page 2</title> </head> <body> <div align="center"><center> <table width="75%" border="0"> <tr> <td width="28%"><img src="daxueshenghuo.jpg" width="156" height="60"> </td> <td width="72%"><img src="ad-baby.gif" width="468" height="60"></td> </tr> </table> <p> </p></center></div><div align="center"><center> <table border="0" cellpadding="0" cellspacing="0" width="50%"> <tr> <td width="100%"><p align="center"><font color="#000080">nksn </font></td> </tr> <tr> <td width="100%"><p align="center"><font color="#000080"> </font></td> </tr> </table> </center></div>

12 Servlet 225 <form method="post" action="zhaopin"> <div align="center"><center><p><font color="#000080"> <select size="1" name="major"> <option value="none" selected=true> </option> <option value="a"> </option> <option value="b"> </option> <option value="c"> </option> <option value="d"> </option> <option value="e"> </option> <option value="f"> </option> <option value="g"> </option> <option value="h"> </option> <option value="i"> </option> <option value="j"> </option> <option value="k"> </option> <option value="l"> </option> <option value="m"> </option> <option value="n"> </option> <option value="o"> </option> <option value="p"> </option> <option value="q"> </option> <option value="r"> </option> <option value="s"> </option> <option value="t"> </option> <option value="u"> </option> <option value="v"> </option> <option value="w"> </option> <option value="x"> </option> <option value="y"> </option> <option value="z"> </option> <option value="aa"> </option> <option value="ab"> </option> <option value="ac"> </option> <option value="ad"> </option> <option value="ae"> </option> <option value="af"> </option> <option value="ag"> </option> <option value="ah"> </option> <option value="ai"> </option> <option value="aj"> </option>

226 Java <option value="ak"> </option> <option value="al"> </option> <option value="am"> </option> <option value="an"> </option> <option value="ao"> </option> <option value="ap"> </option> <option value="aq"> </option> <option value="ar"> </option> </select> <select size="1" name="area"> <option value="none" selected=true> </option> <option value=1> </option> <option value=2> </option> <option value=3> </option> <option value=4> </option> <option value=5> </option> <option value=6> </option> <option value=7> </option> <option value=8> </option> <option value=9> </option> <option value=10> </option> <option value=11> </option> <option value=12> </option> <option value=13> </option> <option value=14> </option> <option value=15> </option> <option value=16> </option> <option value=17> </option> <option value=18> </option> <option value=19> </option> </select></font></p> </center></div><div align="center"><center><p><font color="#000080"><input type="submit" value=" " name="b1"></font></p> </center></div> </form> <p align="center"><font size="2" color="#ff0000"> </font></p>

12 Servlet 227 <p align="center"><font color="#000080"> NKWHT </font></p> <p align="center">(c) XXX<br> copyright Netcore Ltd.2000<br> <a href="mailto:nksn@weonet.com.cn">nksn@weonet.com.cn</a></p> </body> </html> 12.16 <html> 12.16 <head> <meta http-equiv="content-language" content="zh-cn"> <meta http-equiv="content-type" content="text/html; charset=gb2312"> <meta name="generator" content="microsoft FrontPage 4.0"> <meta name="progid" content="frontpage.editor.document"> <title>new Page 2</title> </head> <body bgcolor="#ffffff" text="#000080"> <div align="center"><center> <table width="75%" border="0"> <tr> <td width="27%"><img src="daxueshenghuo.jpg" width="156" height="60">

228 </td> Java <td width="73%"><img src="ad-baby.gif" width="468" height="60"></td> </tr> </table> <p> </p> </center></div> <p align="center"><big>nksn </big></p> <form method="post" action="search" name="shenqing"> <div align="center"><center><p> <select name="sex" size="1"> <option value="none"> </option> <option value="male"> </option> <option value="female"> </option> </select></p> </center></div><div align="center"><center><p> <select size="1" name="major"> <option value="none" selected=true> </option> <option value="1"> </option> <option value="2"> </option> <option value="3"> </option> <option value="4"> </option> <option value="5"> </option> <option value="6"> </option> <option value="7"> </option> <option value="8"> </option> <option value="9"> </option> <option value="10"> </option> <option value="11"> </option> <option value="12"> </option> <option value="13"> </option> <option value="14"> </option> <option value="15"> </option> <option value="16"> </option> <option value="17"> </option> <option value="18"> </option> <option value="19"> </option> <option value="20"> </option> <option value="21"> </option> <option value="22"> </option>

12 Servlet 229 <option value="23"> </option> <option value="24"> </option> <option value="25"> </option> <option value="26"> </option> <option value="27"> </option> <option value="28"> </option> <option value="29"> </option> <option value="30"> </option> <option value="31"> </option> <option value="32"> </option> <option value="33"> </option> <option value="34"> </option> <option value="35"> </option> <option value="36"> </option> <option value="37"> </option> <option value="38"> </option> <option value="39"> </option> <option value="40"> </option> <option value="41"> </option> <option value="42"> </option> <option value="43"> </option> <option value="44"> </option> </select></p> </center></div><div align="center"><center><p> <select size="1" name="yuanji"> <option value="none"> </option> <option value="1"> </option> <option value="2"> </option> <option value="3"> </option> <option value="4"> </option> <option value="5"> </option> <option value="6"> </option> <option value="7"> </option> <option value="8"> </option> <option value="9"> </option> <option value="10"> </option> <option value="11"> </option> <option value="12"> </option> <option value="13"> </option> <option value="14"> </option>

230 Java <option value="15"> </option> <option value="16"> </option> <option value="17"> </option> <option value="18"> </option> <option value="19"> </option> <option value="20"> </option> <option value="21"> </option> <option value="22"> </option> <option value="23"> </option> <option value="24"> </option> <option value="25"> </option> <option value="26"> </option> <option value="27"> </option> <option value="28"> </option> <option value="29"> </option> <option value="29"> </option> <option value="30"> </option> <option value="31"> </option> <option value="32"> </option> <option value="33"> </option> </select> / </p> </center></div><div align="center"><center> <p> <input type="submit" value=" " name="b1"> <input type="reset" value=" " name="b2"> </p> <p>made By NKWHT</p> <p>(c) XXX<br> copyright Netcore Ltd.2000<br> <a href="mailto:nksn@weonet.com.cn">nksn@weonet.com.cn</a></p> </center></div> </form> </body> </html> 12.17 <html> <head>

12 Servlet 231 12.17 <meta http-equiv="content-type" content="text/html; charset=gb2312"> <title> </title> <meta name="generator" content="microsoft FrontPage 4.0"> <meta name="microsoft Border" content="none"> </head> <body bgcolor="#f0fff0" text="#68a05f"> <div align="left"> <table border="0" cellpadding="0" cellspacing="0" width="97%"> <tr> <td width="16%"><img border="0" src="images/nksn.jpg" width="61" height="60"> </td> <td width="39%"><img border="0" src="images/netjob.gif" width="275" height="60"></td> <td width="2%"></td> <td width="48%"><img border="0" src="images/netliuxue.gif" width="273" height="60"></td> </tr> </table> </div> <p align="center"><big> </big></p>

232 Java <form method="post" action="inputzhaopin"> <div align="center"><center><p><input type="radio" value=" " name="r1"> <input type="radio" value=" " name="r2"> <input type="radio" value=" " name="r3"> <input type="radio" value=" " name="r4"> <input type="radio" value=" " name="r5"> </p> </center></div><div align="center"><center><p><input type="radio" value=" " name="r6"> <input type="radio" value=" " name="r7"> <input type="radio" value=" " name="r8"> <input type="radio" value=" " name="r9"> <input type="radio" value=" " name="r10"> </p> </center></div><div align="center"><center><p><input type="radio" value=" " name="r11"> <input type="radio" value=" " name="r12"> <input type="radio" value=" " name="r13"> <input type="radio" value=" " name="r14"> <input type="radio" value=" " name="r15"> <input type="radio" value=" " name="r16"> </p> </center></div><div align="center"><center><p><input type="radio" value=" " name="r17"> <input type="radio" value=" " name="r18"> <input type="radio" value=" " name="r19"> <input type="radio" value=" " name="r20"> <input type="radio" value=" " name="r21"> <input type="radio" value=" " name="r22"> </p> </center></div><div align="center"><center><p><input type="radio" value=" " name="r23"> <input type="radio" value=" " name="r24"> <input type="radio" value=" " name="r25"> <input type="radio" value=" " name="r26"> <input type="radio" value=" " name="r27"> <input type="radio" value=" " name="r28"> <input type="radio" value=" " name="r29"> </p> </center></div><div align="center"><center><p><input type="radio" value=" " name="r30"> <input type="radio" value=" " name="r31"> <input type="radio" value=" " name="r32"> <input type="radio" value=" " name="r33"> <input type="radio" value=" " name="r34"> </p> </center></div><div align="center"><center><p><input type="radio" value=" " name="r35"> <input type="radio" value=" " name="r36"> <input type="radio" value=" " name="r37"> <input type="radio"

12 Servlet 233 value=" " name="r38"> <input type="radio" value=" " name="r39"> </p> </center></div><div align="center"><center><p><input type="radio" value=" " name="r40"> <input type="radio" value=" " name="r41"> <input type="radio" value=" " name="r42"> <input type="radio" value=" " name="r43"> <input type="radio" value=" " name="r44"> </p> </center></div><div align="center"><center><p> <select name="area" size="1"> <option value="1"> </option> <option value="2"> </option> <option value="3"> </option> <option value="4"> </option> <option value="5"> </option> <option value="6"> </option> <option value="7"> </option> <option value="8"> </option> <option value="9"> </option> <option value="10"> </option> <option value="11"> </option> <option value="12"> </option> <option value="13"> </option> <option value="14"> </option> <option value="15"> </option> <option value="16"> </option> <option value="17"> </option> <option value="18"> </option> <option value="19"> </option> </select> <input type="text" name="company" size="30"></p> </center></div><div align="center"><center><p> </p> </center></div><div align="center"><center><p><textarea rows="5" name="content" cols="26"></textarea></p> </center></div><div align="center"><center><p><input type="submit" value=" " name="b1"><input type="reset" value=" " name="b2"></p> </center></div> </form> </body> </html> 12.18

234 Java 12.18 <html> <head> <meta http-equiv="content-language" content="zh-cn"> <meta http-equiv="content-type" content="text/html; charset=gb2312"> <meta name="generator" content="microsoft FrontPage 4.0"> <meta name="progid" content="frontpage.editor.document"> <title>new Page 2</title> </head> <script language="vbscript"> sub ok() if(trim(document.forms(0).elements(0).value)<>"" trim(document.forms(0).elements(1).value)<>"" trim(document.forms(0).elements(2).value)<>"" trim(document.forms(0).elements(6).value)<>"" trim(document.forms(0).elements(7).value)<>"" trim(document.forms(0).elements(8).value)<>"" trim(document.forms(0).elements(9).value)<>"" trim(document.forms(0).elements(11).value)<>"" instr(document.forms(0).elements(11).value,"<")=0) then document.forms(0).submit() and and and and and and and and

12 Servlet 235 else end if end sub alert "!" </script> <body bgcolor="#ffffff" text="#000080"> <div align="center"><center> <table width="75%" border="0"> <tr> <td width="28%"><img src="daxueshenghuo.jpg" width="156" height="60"> </td> <td width="72%"><img src="ad-baby.gif" width="468" height="60"></td> </tr> </table> <p> </p> </center> </div> <p align="center"><big>nksn </big></p> <form method="post" action="zhuche " name="shenqing"> <div align="center"><center> <p> <input type="text" name="zhanghao" size="10"> <input type="password" name="mima" size="10"> </p> </center> </div> <div align="center"></div> <div align="center"><center> <p> <input type="text" name="name" size="10">

236 Java <input type="radio" value="male" checked name="male"> <input type="radio" name="male" value="female"> </p> </center> </div> <div align="center"> <center> </center></div><div align="center"><center> <p> <select size="1" name="major"> <option value="1"> </option> <option value="2"> </option> <option value="3"> </option> <option value="4"> </option> <option value="5"> </option> <option value="6"> </option> <option value="7"> </option> <option value="8"> </option> <option value="9"> </option> <option value="10"> </option> <option value="11"> </option> <option value="12"> </option> <option value="13"> </option> <option value="14"> </option> <option value="15"> </option> <option value="16"> </option> <option value="17"> </option> <option value="18"> </option> <option value="19"> </option> <option value="20"> </option> <option value="21"> </option> <option value="22"> </option> <option value="23"> </option> <option value="24"> </option> <option value="25"> </option> <option value="26"> </option>

12 Servlet 237 <option value="27"> </option> <option value="28"> </option> <option value="29"> </option> <option value="30"> </option> <option value="31"> </option> <option value="32"> </option> <option value="33"> </option> <option value="34"> </option> <option value="35"> </option> <option value="36"> </option> <option value="37"> </option> <option value="38"> </option> <option value="39"> </option> <option value="40"> </option> <option value="41"> </option> <option value="42"> </option> <option value="43"> </option> <option value="44"> </option> </select> <input type="text" name="lou" size="2"> <input type="text" name="room" size="3"> </p> </center> </div> <div align="center"> <center> </center></div><div align="center"><center> <p> <input type="text" name="tel" size="15"> E-MAIL <input type="text" name="mail" size="30"> </p> </center> </div> <div align="center">

238 Java <center> </center></div><div align="center"><center><p> <select size="1" name="yuanji"> <option value="1"> </option> <option value="2"> </option> <option value="3"> </option> <option value="4"> </option> <option value="5"> </option> <option value="6"> </option> <option value="7"> </option> <option value="8"> </option> <option value="9"> </option> <option value="10"> </option> <option value="11"> </option> <option value="12"> </option> <option value="13"> </option> <option value="14"> </option> <option value="15"> </option> <option value="16"> </option> <option value="17"> </option> <option value="18"> </option> <option value="19"> </option> <option value="20"> </option> <option value="21"> </option> <option value="22"> </option> <option value="23"> </option> <option value="24"> </option> <option value="25"> </option> <option value="26"> </option> <option value="27"> </option> <option value="28"> </option> <option value="29"> </option> <option value="29"> </option> <option value="30"> </option> <option value="31"> </option> <option value="32"> </option> <option value="33"> </option> </select> / </p> </center></div><div align="center"><center><p> (<font color="#ff0000"> <small> HTML</small></font>)</p>

12 Servlet 239 </center></div><div align="center"><center><p><textarea rows="11" name="jianjie" cols="47"></textarea></p> </center></div><div align="center"><center> <p> <input type="button" value=" " name="su" onclick="ok()"> <input type="reset" value=" " name="res"> </p> <p>(c) XXXX<br> copyright Netcore Ltd.2000<br> <a href="mailto:nksn@weonet.com.cn">nksn@weonet.com.cn</a></p> </center></div> </form> </body> </html> 12.19 12.19 <html> <head> <meta http-equiv="content-language" content="en-us"> <meta http-equiv="content-type" content="text/html; charset=gb2312">

240 Java <meta name="generator" content="microsoft FrontPage 4.0"> <meta name="progid" content="frontpage.editor.document"> <title>new Page 1</title> </head> <script language="javascript"> function ok() if(document.forms(0).elements(0).value!="" document.forms(0).elements(1). value!="") document.forms(0).submit(); && else alert("!"); document.forms(0).reset(); </script> <body bgcolor="#ffffff"> <div align="center"><center> <table width="75%" border="0"> <tr> <td width="28%"><img src="daxueshenghuo.jpg" width="156" height="60"> </td> <td width="72%"><img src="ad-baby.gif" width="468" height="60"></td> </tr> </table> <p> </p> </center></div> <p align="center"><font color="#000080"><big><big> </big></big></font></p> <form method="post" action="edit.asp"> <div align="center"><center><p><font color="#000080"> <input type="text" name="name" size="10"></font></p> </center></div><div align="center"><center><p><font color="#000080"> <input type="text" name="zhanghao" size="10"></font></p> </center></div><div align="center"><center><p><font color="#000080"> <input type="password" name="mima" size="10"></font></p>

12 Servlet 241 </center></div><div align="center"><center><p><input type="button" value=" " name="b1" onclick="ok()"><input type="reset" value=" " name="b2"></p> </center></div> <p align="center">made By NKWHT</p> <p align="center">(c) XXXXX<br> copyright Netcore Ltd.2000<br> <a href="mailto:nksn@weonet.com.cn">nksn@weonet.com.cn</a> </p> </form> </body> </html> 12.20 12.20 Servlet zhuce.java import java.io.*; import java.text.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import java.net.url; import java.sql.*; public class GuestBook extends HttpServlet

242 Java Connection con; public void init(servletconfig conf) throws ServletException super.init();// String l="jdbc:odbc:employer"; try Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con=drivermanager.getconnection(l,"sa",""); catch(exception e) // public void doget(httpservletrequest request, HttpServletResponse response) throws IOException, ServletException // String zhanghao=string.(request.getparameter("zhanghao")); String mima=string.(request.getparameter("mima")); String name=string.(request.getparameter("name")); String jianjie= request.getparameter("jianjie"); String major=request.getparameter("major") ; String sex=request.getparameter("male"); String building=string.(request.getparameter("lou")); String room=string.(request.getparameter("room")); String tel=string.(request.getparameter("tel")); String mail=string.(request.getparameter("mail")); String yuanji=string.(request.getparameter("yuanji")); PrintWriter out = response.getwriter(); out.println("<html>"); out.println("<body>"); out.println("<head>"); if( name!="" && major!="" && building!="" && mail!="" && room!="" && tel!="" && zhanghao!="" && mima!="" && jianjie.indexof("<")==0) //, // try

12 Servlet 243 Statement stmt = con.createstatement(); String sql="insert Employer values(zhanghao,mima, major,sex,building,room,tel,mail,yuanji)"; stmt.executeupdate(sql); con.close(); response.setcontenttype("text/html"); out.println("<title> </title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>!!</h1>"); catch(sqlexception ex) while(ex!=null) out.println(" "); out.println(ex.getsqlstate()); out.println(ex.getmessage()); out.println(ex.geterrorcode()); ex=ex.getnextexception(); else //, out.println("<title> </title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>,,!</h1>"); out.println("</body>"); out.println("</html>"); return ; out.println("</body>"); out.println("</html>"); 12.21( ) 12.22

244 Java 12.21 12.22 zhaopin.java import java.io.*; import java.text.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import java.net.url; import java.sql.*;

12 Servlet 245 public class GuestBook extends HttpServlet Connection con; public void init(servletconfig conf) throws ServletException super.init();// String l="jdbc:odbc:employer"; try Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con=drivermanager.getconnection(l,"sa",""); catch(exception e) // public void doget(httpservletrequest request, HttpServletResponse response) throws IOException, ServletException String major=request.getparameter("major") String add=request.getparameter("area") String sql; if (major=="none" && add=="none" ) sql=="select number,area from zhuanzhi" else if (major=="none" && add!=="none") sql=="select number,area from zhuanzhi where area==" & add else if (major!=="none" && add!=="none" ) sql=="select number,area from zhuanzhi where area==" & add & "&& " & major & "==true" else if (major!=="none" && add=="none" ) sql=="select number,area from zhuanzhi where " & major & "==True" response.setcontenttype("text/html"); PrintWriter out = response.getwriter(); out.println("<html>"); out.println("<body>"); out.println("<head>"); out.println("p align="center"> </p>");

246 Java // html try Statement stmt = con.createstatement(); ResultSet res=stmt.executequery(sql); if(!res.eof()) // String table_string="<table border='1' width='100%'> <tr> <td width='15%' align='center'> </td> <td width='58%' align='center'> </td> <td width='27%' align='center'> </td> </tr> </table>" out.println(table_string); // while(res.getnext()) // table_string="<table border='1' width='100%'> <tr> <td width='15%' align='center'> <a href='zhaopinresult?mode=" + res.getstring("number") +"'>" + res.getstring("number") + "</a></td> <td width='58%' align='center'>" + res.getstring("company") + "</td> <td width='27%' align='center'>" + res.getstring("area") + "</td></tr> </table>"; out.println(table_string); else out.println("<p align=center><font color=red>,!</font></p>"); catch(sqlexception ex) while(ex!=null)

12 Servlet 247 out.println(" "); out.println(ex.getsqlstate()); out.println(ex.getmessage()); out.println(ex.geterrorcode()); ex=ex.getnextexception(); out.println("</body>"); out.println("</html>"); 12.23 12.24 12.23 12.24

248 Java zhaopinresult.java import java.io.*; import java.text.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import java.net.url; import java.sql.*; public class GuestBook extends HttpServlet Connection con; public void init(servletconfig conf) throws ServletException super.init();// String l="jdbc:odbc:employer"; try Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con=drivermanager.getconnection(l,"sa",""); catch(exception e) // public void doget(httpservletrequest request, HttpServletResponse response) throws IOException, ServletException String key=request.getparameter("mode"); // String sql="select * from employer where number='" + key + "'"; response.setcontenttype("text/html"); PrintWriter out = response.getwriter(); out.println("<html>"); out.println("<body>"); out.println("<head>"); out.println("p align="center"> </p>"); // html try

12 Servlet 249 Statement stmt = con.createstatement(); ResultSet res=stmt.executequery(sql); if(!res.eof()) // String table_string="<p align="center"><font size="4" color="#679966"> </font></p>" // out.println(table_string); // table_string=<p align='center'> </p> <div align='center'><center> <table border='1' width='84%'> <tr> <td width='100%'><p align='center'>" +res.getparameter("content") + "</td> </tr> </table> </center></div>"; out.println(table_string); else out.println("<p align=center><font color=red>,!</font></p>"); catch(sqlexception ex) while(ex!=null) out.println(" "); out.println(ex.getsqlstate()); out.println(ex.getmessage()); out.println(ex.geterrorcode()); ex=ex.getnextexception(); table_string="<p align='center'> <a href='javascript:void(0)' onclick='window.history.back()'> </a>&nbsp

250 Java <a href='zhaopin.htm'> </a></p>" ; out.println(table_string); out.println("</body>"); out.println("</html>"); 12.25 12.26 12.25 12.26 search.java import java.io.*; import java.text.*; import java.util.*;

12 Servlet 251 import javax.servlet.*; import javax.servlet.http.*; import java.net.url; import java.sql.*; public class Search extends HttpServlet Connection con; public void init(servletconfig conf) throws ServletException super.init();// String l="jdbc:odbc:employer"; try Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con=drivermanager.getconnection(l,"sa",""); catch(exception e) // public void doget(httpservletrequest request, HttpServletResponse response) throws IOException, ServletException String major=request.getparameter("major") String sex=request.getparameter("sex"); String yuanji=request.getparameter("yuanji"); String sql="select zhanghao,major,sex from employer"; if ( sex!="none" and major!="none" and yuanji!="none" ) sql="select zhanghao,sex,major from employer where major=" & major & "and sex='" & sex & "' and yuanji=" & yuanji ; else if ( major!="none" and sex="none" and yuanji!="none" ) sql="select zhanghao,sex,major from employer where major=" & major & "and yuanji=" & yuanji ; else if ( major="none" and sex!="none" and yuanji="none" ) sql="select zhanghao,sex,major from employer where sex='" & sex & "'"; else if ( major="none" and sex="none" and yuanji!="none" )

252 Java sql="select zhanghao,sex,major from employer where yuanji=" & yuanji; else if ( major="none" and sex!="none" and yuanji!="none" ) sql="select zhanghao,sex,major from employer where sex='" & sex & "'and yuanji=" & yuanji; else if ( major!="none" and sex!="none" and yuanji="none" ) sql="select zhanghao,sex,major from employer where major=" & major & " and sex='" & sex & "'"; else if ( major!="none" and sex="none" and yuanji="none" ) sql="select zhanghao,sex,major from employer where major=" & major ; else if ( major="none" and sex!="none" and yuanji="none" ) sql="select zhanghao,sex,major from employer where sex='" & sex & "'"; response.setcontenttype("text/html"); PrintWriter out = response.getwriter(); out.println("<html>"); out.println("<body>"); out.println("<head>"); out.println("p align="center"> </p>"); // html try Statement stmt = con.createstatement(); ResultSet res=stmt.executequery(sql); if ((!res.eof()) // while(res.getnext()) // table_string="<table border='1' width='100%'> <tr> <td width='15%' align='center'> <a href='result?mode=" + res.getstring("zhanghao") +"'>" + res.getstring("sex") + "</a></td> <td width='58%' align='center'>" + res.getstring("major") + "</td> <td width='27%' align='center'>" + res.getstring("area") +

12 Servlet 253 "</td></tr> </table>"; out.println(table_string); else out.println("<p align=center><font color=red>,!</font></p>"); catch(sqlexception ex) while(ex!=null) out.println(" "); out.println(ex.getsqlstate()); out.println(ex.getmessage()); out.println(ex.geterrorcode()); ex=ex.getnextexception(); out.println("</body>"); out.println("</html>"); 12.27 12.28 12.27

254 Java 12.28 result.java import java.io.*; import java.text.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import java.net.url; import java.sql.*; public class Result extends HttpServlet Connection con; public void init(servletconfig conf) throws ServletException super.init();// String l="jdbc:odbc:employer"; try Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con=drivermanager.getconnection(l,"sa",""); catch(exception e) // public void doget(httpservletrequest request, HttpServletResponse response) throws IOException, ServletException String key=request.getparameter("key");

12 Servlet 255 String sql="select * from employer where zhanghao='" & key & "'"; response.setcontenttype("text/html"); PrintWriter out = response.getwriter(); out.println("<html>"); out.println("<body>"); out.println("<head>"); out.println("p align="center"> </p>"); // html try Statement stmt = con.createstatement(); ResultSet res=stmt.executequery(sql); if ((!res.eof()) // String name=res.getstring("name"); // String sex=res.getstring("sex"); // String major=res.getstring("major"); // String tel=res.getstring("tel"); // String mail=res.getstring("mail"); // String builder=res.getstring("building"); // String room=res.getstring("room"); // String yuanji=res.getstring("yuanji"); // String jianjie=res.getstring("jianjie"); // String table_string=/* */ "<div align='center'><center> <table width='75%' border='0'> <tr> <td width='28%'><img src='daxueshenghuo.jpg' width='156' height='60'></td> <td width='72%'><img src='ad-baby.gif' width='468' height='60'></td>

256 Java </tr> </table> <p> </p> </center> </div> <p align='center'><font size='4' color='#679966'> </font></p> <table border='1' width='100%'> <tr> <td width='33%' align='center'><p align='center'> </td> <td width='33%' align='center'> </td> <td width='34%' align='center'> </td> </tr> <tr> <td width='33%' align='center'>"+name+" </td> <td width='33%' align='center'>"+sex+" </td> <td width='34%' align='center'>"+major+" </td> </tr> </table> <table border='1' width='100%'> <tr> <td width='50%' align='center'> </td> <td width='50%' align='center'> </td> </tr> <tr> <td width='50%' align='center'>"+res('tel')+" </td> <td width='50%' align='center'>"+res('mail')+" </td> </tr> <tr> <td width='50%' align='center'> </td> <td width='50%' align='center'> </td> </tr> <tr>

12 Servlet 257 <td width='50%' align='center'>"+building+" "+' '+" "+room+" </td> <td width='50%' align='center'>"+yuanji+" </td> </tr> </table> <p align='center'> </p> <div align='center'><center> <table border='1' width='84%'> <tr> <td width='100%'><p align='center'>"+jianjie+"</td> </tr> </table> </center></div>"; out.println(table_string); else out.println("<p align=center><font color=red>,!</font></p>"); catch(sqlexception ex) while(ex!=null) out.println(" "); out.println(ex.getsqlstate()); out.println(ex.getmessage()); out.println(ex.geterrorcode()); ex=ex.getnextexception(); out.println("</body>"); out.println("</html>");

258 Java 12.29 12.30 12.29 12.30 masterinput.java import java.io.*; import java.text.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import java.net.url; import java.sql.*; public class Result extends HttpServlet Connection con; public void init(servletconfig conf) throws ServletException

12 Servlet 259 super.init();// String l="jdbc:odbc:employer"; try Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con=drivermanager.getconnection(l,"sa",""); catch(exception e) // public void doget(httpservletrequest request, HttpServletResponse response) throws IOException, ServletException response.setcontenttype("text/html"); PrintWriter out = response.getwriter(); out.println("<html>"); out.println("<body>"); out.println("<head>"); out.println("p align="center"> </p>"); // html try Statement stmt = con.createstatement(); bool res[44]; // true if request.getparameter("r1")!="" res[0)=true; else res[0)=false; if request.getparameter("r2")!="" res[1)=true; else res[1)=false; if request.getparameter("r3")!="" res[2)=true; else res[2)=false;

260 Java if request.getparameter("r4")!="" res[3)=true; else res[3)=false; if request.getparameter("r5")!="" res[4)=true; else res[4)=false; if request.getparameter("r6")!="" res[5)=true; else res[5)=false; if request.getparameter("r7")!="" res[6)=true; else res[6)=false; if request.getparameter("r8")!="" res[7)=true; else res[7)=false; if request.getparameter("r9")!="" res[8)=true; else res[8)=false; if request.getparameter("r10")!="" res[9)=true; else res[9)=false; if request.getparameter("r11")!="" res[10)=true; else res[10)=false;

12 Servlet 261 if request.getparameter("r12")!="" res[11)=true; else res[11)=false; if request.getparameter("r13")!="" res[12)=true; else res[12)=false; if request.getparameter("r14")!="" res[13)=true; else res[13)=false; if request.getparameter("r15")!="" res[14)=true; else res[14)=false; if request.getparameter("r16")!="" res[15)=true; else res[15)=false; if request.getparameter("r17")!="" res[16)=true; else res[16)=false; if request.getparameter("r18")!="" res[17)=true; else res[17)=false; if request.getparameter("r19")!="" res[18)=true; else res[18)=false; if request.getparameter("r20")!=""

262 Java else res[19)=true; res[19)=false; if request.getparameter("r21")!="" res[20)=true; else res[20)=false; if request.getparameter("r22")!="" res[21)=true; else res[21)=false; if request.getparameter("r23")!="" res[22)=true; else res[22)=false; if request.getparameter("r24")!="" res[23)=true; else res[23)=false; if request.getparameter("r25")!="" res[24)=true; else res[24)=false; if request.getparameter("r26")!="" res[25)=true; else res[25)=false; if request.getparameter("r27")!="" res[26)=true; else res[26)=false; if request.getparameter("r28")!=""

12 Servlet 263 else res[27)=true; res[27)=false; if request.getparameter("r29")!="" res[28)=true; else res[28)=false; if request.getparameter("r30")!="" res[29)=true; else res[29)=false; if request.getparameter("r31")!="" res[30)=true; else res[30)=false; if request.getparameter("r32")!="" res[31)=true; else res[31)=false; if request.getparameter("r33")!="" res[32)=true; else res[32)=false; if request.getparameter("r34")!="" res[33)=true; else res[33)=false; if request.getparameter("r35")!="" res[34)=true; else res[34)=false; if request.getparameter("r36")!="" res[35)=true;

264 Java else res[35)=false; if request.getparameter("r37")!="" res[36)=true; else res[36)=false; if request.getparameter("r38")!="" res[37)=true; else res[37)=false; if request.getparameter("r39")!="" res[38)=true; else res[38)=false; if request.getparameter("r40")!="" res[39)=true; else res[39)=false; if request.getparameter("r41")!="" res[40)=true; else res[40)=false; if request.getparameter("r42")!="" res[41)=true; else res[41)=false; if request.getparameter("r43")!="" res[42)=true; else res[42)=false; if request.getparameter("r44")!="" res[43)=true;

12 Servlet 265 else res[43)=false; String company=request.getparameter("company"); // String area=request.getparameter("area"); // String sql="insert zhaopin values("; for(int i=0;i<44;i++) sql+=res[i] + ","; // sql+="'"+ company+ "','" + area + "')"; // sql, stmt.executeupdate(sql); out.println("<p align=center><font color=red>!</font></p>"); catch(sqlexception ex) while(ex!=null) out.println(" "); out.println(ex.getsqlstate()); out.println(ex.getmessage()); out.println(ex.geterrorcode()); ex=ex.getnextexception(); out.println("</body>"); out.println("</html>"); 12.31 edit.java import java.io.*; import java.text.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import java.net.url;

266 Java 12.31 import java.sql.*; public class Edit extends HttpServlet Connection con; public void init(servletconfig conf) throws ServletException super.init();// String l="jdbc:odbc:employer"; try Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con=drivermanager.getconnection(l,"sa",""); catch(exception e) // public void doget(httpservletrequest request, HttpServletResponse response) throws IOException, ServletException String name=request.getparameter("name"); // String password=request.getparameter("mima"); // String sql="select password from employer where zhanghao='" & name & "'"; response.setcontenttype("text/html"); PrintWriter out = response.getwriter();

12 Servlet 267 out.println("<html>"); out.println("<body>"); out.println("<head>"); out.println("p align="center"> </p>"); // html try Statement stmt = con.createstatement(); ResultSet res=stmt.executequery(sql); if ((!res.eof()) // String pass=res.getstring("pass"); if(password==pass) out.println("<h1>,!</h1>"); else out.println("<p align=center><font color=red>,!</font> </p>"); else out.println("<p align=center><font color=red>,!</font></p>"); catch(sqlexception ex) while(ex!=null) out.println(" "); out.println(ex.getsqlstate()); out.println(ex.getmessage()); out.println(ex.geterrorcode()); ex=ex.getnextexception(); out.println("</body>"); out.println("</html>"); 12.32~ 12.34

268 Java 12.32 12.33 12.34 editmore.java import java.io.*; import java.text.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*;

12 Servlet 269 import java.net.url; import java.sql.*; public class EditMore extends HttpServlet Connection con; public void init(servletconfig conf) throws ServletException super.init();// String l="jdbc:odbc:employer"; try Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con=drivermanager.getconnection(l,"sa",""); catch(exception e) // public void doget(httpservletrequest request, HttpServletResponse response) throws IOException, ServletException String mode=request.getparameter("mode"); String sql="select * from employer where zhangha='" + mode + "'"; response.setcontenttype("text/html"); PrintWriter out = response.getwriter(); out.println("<html>"); out.println("<body>"); out.println("<head>"); out.println("p align="center"> </p>"); // html try Statement stmt = con.createstatement(); ResultSet res=stmt.executequery(sql); // String mima=res.getstring("password"); // String lou=res.getstring("building");

270 Java String room=res.getstring("room"); String tel=res.getstring("tel"); String mail=res.getstring("mail"); String jianjie=res.getstring("jianjie"); res.close(); // String table_string=/* */ "<body bgcolor='#ffffff' text='#000080'> <div align='center'><center> <table width='75%' border='0'> <tr> <td width='28%'> <img src='daxueshenghuo.jpg' width='156' height='60'> </td> <td width='72%'> <img src='ad-baby.gif' width='468' height='60'> </td> </tr> </table> </center></div> <form method='post' action='editover' name='shenqing'> <div align='center'> <center><p> <input type='password' name='mima' size='10' value='"+mima+"'> </p> </center></div> <div align='center'> <center><p> <input type='text' name='name' size='10' value='"+name+"'></p> </center></div> <div align='center'> <center><p> <input type='text' name='lou' size='2' value='"+lou+"'> <input type='text' name='room' size='3' value='"+room+"'> </p>

12 Servlet 271 </center></div> <div align='center'> <center><p> <input type='text' name='tel' size='15' value='"+tel+"'></p> </center></div> <div align='center'><center><p> E-MAIL<input type='text' name='mail' size='30' value='"+mail+"'></p> </center></div> <div align='center'><center> <p> </p> </center></div> <div align='center'> <center><p><textarea rows='11' name='jianjie' cols='47'>"+jianjie+"</textarea></p> </center></div> <div align='center'><center> <p> <input type='submit' value=' '> <input type='reset' value=' '> </p> <p>(c) XXXXXXX<br> copyright Netcore Ltd.2000<br> <a href='mailto:nksn@weonet.com.cn'>nksn@weonet.com.cn</a></p> </center></div> </form>" out.println(table_string); catch(sqlexception ex) while(ex!=null) out.println(" "); out.println(ex.getsqlstate()); out.println(ex.getmessage()); out.println(ex.geterrorcode()); ex=ex.getnextexception();

272 Java out.println("</body>"); out.println("</html>"); 12.35 12.35 editover.java import java.io.*; import java.text.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import java.net.url; import java.sql.*; public class EditOver extends HttpServlet Connection con; public void init(servletconfig conf) throws ServletException super.init();// String l="jdbc:odbc:employer"; try Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con=drivermanager.getconnection(l,"sa",""); catch(exception e)

12 Servlet 273 // public void doget(httpservletrequest request, HttpServletResponse response) throws IOException, ServletException String jianjie=request.getparameter("jianjie"); String password=request.getparameter("mima"); String name=request.getparameter("name") ; String building=request.getparameter("lou"); String room=request.getparameter("room"); String tel=request.getparameter("tel"); String mail=request.getparameter("mail"); response.setcontenttype("text/html"); PrintWriter out = response.getwriter(); out.println("<html>"); out.println("<body>"); out.println("<head>"); out.println("p align="center"> </p>"); // html if( name!=""&& building!="" && mail!="" && room!="" && tel!="" && password!="" && jianjie!="" ) String sql="update employer set values(name='" + name"',building='" +building + "',mail='" + mail + "',room='" + room + "', tel='" + tel + "',password='" + mima + "')"; // sql try Statement stmt = con.createstatement(); stmt.executeupdate(sql); out.println("<h1>!</h1>"); else out.println("<p align=center><font color=red>,!</font></p>"); catch(sqlexception ex)

274 Java while(ex!=null) out.println(" "); out.println(ex.getsqlstate()); out.println(ex.getmessage()); out.println(ex.geterrorcode()); ex=ex.getnextexception(); out.println("</body>"); out.println("</html>"); 12.36 12.37 12.36 12.37 Servlet JDBC

12 Servlet 275 12.4 1 2 IMG HTML 3 SQL JDBC 4

13 Java Server Pages Servlet JSP HTML 13.1 JSP JDBC Servlet Java Java Sun JSP 1 JSP JSP Java Java Java Web Java Servlet JSP Java Web Java Java Java Jsp Servlet Java Java Web Java Bean EJB Java Application Server Java 2 JSP JSP JSP Java Java HTTPServlet <jsp:* <%@ URL JavaBean JSP Java Servlet Servlet JSP Java Servlet JSP Java Servlet Code(.java ) Java Runtime Bin Code(.class ) JSP CPU JSP Java Java class JSP class Java JSP ASP JSP

13 Java Server Pages 277 3 JSP (1) java php (2) Java servlet/jsp Web Server/Application Server... Asp/php (3) Jar Servlet/JSP Application... Java (4) Asp Java 4 JSP JSP (1) ASP Java Java jre jdk jsdk jswdk... (2) JSP (3) Java class.java.class 13.2 JSP JSP Java Java Java JSP 13.2.1 JSP HTML TAG TAG <% %> JSP "Thanks for ordering Core Web Programming"

278 Java http://host/orderconfirmation.jsp?title=core+web+programming: Thanks for ordering <I><%= request.getparameter("title") %></I>.jsp Servlet Servlet servlet web HTML Servlet JSP HTML JSP Servlet Java Servlet BEAN JSP JSP JSP1.0 0.92 1.0 0.92 1.0 13-1 JSP JSP JSP <%= %> JSP <% %> service JSP <%! %> Servlet service JSP <%@ page att="val" %> SERVLET JSP include <%@ include file="url" %> Servlet JSP <%-- --%> JSP SERVLET jsp:include <jsp:include page="relative URL"flush="true"/> jsp:usebean <jsp:usebean att=val*/> or <jsp:usebean att=val*>... </jsp:usebean> Java BEAN jsp:setproperty <jsp:setproperty att=val*/> bean jsp:getproperty jsp:forward jsp:plugin 13.2.2 JSP <jsp:getproperty name="propertyname" value="val"/> <jsp:forward page="relative URL"/> <jsp:plugin attribute="value"*>... </jsp:plugin> bean OBJECT, APPLET PLUGIN JSP Java JSP Servlet <%= %> <% %> Servlet <%! %> Servlet

13 Java Server Pages 279 1 Java <%= Java %> Java / : <%= new java.util.date() %> 13.1 13.1 JSP request, the HttpServletRequest; response, the HttpServletResponse; session, the HttpSession associated with the request (if any); and out, the PrintWriter (a buffered version of type JspWriter) <%= request.getremotehost() %> 13.2 XML <jsp:expression> Java </jsp:expression> XML 2 JSP Scriptlets scriptlets Java Servlet <% %>

280 Java 13.2 scriptlets out <% String querydata = request.getquerystring(); out.println("attached GET data: " + querydata); %> Servlet Java <% if (Math.random() < 0.5) %> Have a <B>nice</B> day! <% else %> Have a <B>lousy</B> day! <% %> if (Math.random() < 0.5) out.println("have a <B>nice</B> day!"); else out.println("have a <B>lousy</B> day!"); %> %\> XML <% %> <jsp:scriptlet>

13 Java Server Pages 281 </jsp:scriptlet> 13.3 JSP 13.3 3 JSP JSP Servlet <%! %> JSP JSP JSP SERVLET <%! private int accesscount = 0; %> Accesses to page since server reboot: <%= ++accesscount %> JSP %> %\> XML <jsp:declaration> Code </jsp:declaration> 13.4 4 JSP JSP Servlet <%@ directive attribute="value" %> <%@ directive attribute1="value1" attribute2="value2" attributen="valuen" %>

282 Java 13.4 6 JSP page, Servlet include Servlet JSP1.1 JSP1.1 (1) JSP page page import="package.class" or import="package.class1,...,package.classn" <%@ page import="java.util.*" %> import contenttype="mime-type" or contenttype="mime-type; charset=character-set" MIME text/html <%@ page contenttype="text/plain" %> <% response.setcontenttype("text/plain"); %> isthreadsafe="true false". true ( ) Servlet false SERVLET SingleThreadModel, session="true false". true ( ) session (of type HttpSession) Session false session, session JSP SERVLET buffer="sizekb none" JspWriter out 8KB autoflush="true false". true false buffer="none" extends="package.class". Servlet

13 Java Server Pages 283 info="message" getservletinfo errorpage="url" iserrorpage="true false". false. language="java". Java XML <jsp:directive.directivetype attribute=value /> <%@ page import="java.util.*" %> XML <jsp:directive.page import="java.util.*" /> (2) JSP include Include JSP Servlet <%@ include file="relative url" %> JSP Include JSP FRAME TABLE Include <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE>Servlet Tutorial: JavaServer Pages (JSP) 1.0</TITLE> <META NAME="author" CONTENT="webmaster@somesite.com"> <META NAME="keywords" CONTENT="..."> <META NAME="description" CONTENT="..."> <LINK REL=STYLESHEET HREF="Site-Styles.css" TYPE="text/css"> </HEAD> <BODY> <%@ include file="/navbar.html" %> <!-- Part specific to this page... --> </BODY> </HTML> Include JSP Include ACTION jsp:include

284 Java ASP JSP ASP JSP JSP <HTML> <HEAD> <TITLE>Using JavaServer Pages</TITLE> <META NAME="author" CONTENT="Marty Hall -- hall@apl.jhu.edu"> <META NAME="keywords" CONTENT="JSP,JavaServer Pages,servlets"> <META NAME="description" CONTENT="A quick example of the four main JSP tags."> <LINK REL=STYLESHEET HREF="My-Style-Sheet.css" TYPE="text/css"> </HEAD> <BODY BGCOLOR="#FDF5E6" TEXT="#000000" LINK="#0000EE" VLINK="#551A8B" ALINK="#FF0000"> <CENTER> <TABLE BORDER=5 BGCOLOR="#EF8429"> <TR><TH CLASS="TITLE"> Using JavaServer Pages</TABLE> </CENTER> <P> Some dynamic content created using various JSP mechanisms: <UL> <LI><B>Expression.</B><BR> Your hostname: <%= request.getremotehost() %>. <LI><B>Scriptlet.</B><BR> <% out.println("attached GET data: " + request.getquerystring()); %> <LI><B>Declaration (plus expression).</b><br> <%! private int accesscount = 0; %> Accesses to page since server reboot: <%= ++accesscount %> <LI><B>Directive (plus expression).</b><br> <%@ page import = "java.util.*" %> Current date: <%= new Date() %>

13 Java Server Pages 285 </UL> </BODY> </HTML> 13.5 13.5 5 JSP XML Servlet Java Bean Java HTML PLUGIN jsp:include jsp:usebean JavaBean jsp:setproperty JavaBean jsp:getproperty Java Bean jsp:forward jsp:plugin (1) jsp:include <jsp:include page="relative URL" flush="true" /> include directive, Servlet, Servlet JSP JSP 4 What's New?

286 Java <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE>What's New</TITLE> <LINK REL=STYLESHEET HREF="My-Style-Sheet.css" TYPE="text/css"> </HEAD> <BODY BGCOLOR="#FDF5E6" TEXT="#000000" LINK="#0000EE" VLINK="#551A8B" ALINK="#FF0000"> <CENTER> <TABLE BORDER=5 BGCOLOR="#EF8429"> <TR><TH CLASS="TITLE"> What's New at JspNews.com</TABLE> </CENTER> <P> Here is a summary of our four most recent news stories: <OL> <LI><jsp:include page="item1.html" flush="true"/> <LI><jsp:include page="item2.html" flush="true"/> <LI><jsp:include page="item3.html" flush="true"/> <LI><jsp:include page="item4.html" flush="true"/> </OL> </BODY> </HTML> (2) jsp:usebean JavaBean Java bean <jsp:usebean id="name" class="package.class" /> class id scope Bean Bean usebean id scope Bean jsp:setproperty scriptlet id Bean foo x getfoo

13 Java Server Pages 287 x setfoo jsp:setproperty getxxx jsp:getproperty Bean Java Web Server Bean jar servlets Bean / BeanTest.jsp <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE>Reusing JavaBeans in JSP</TITLE> <LINK REL=STYLESHEET HREF="My-Style-Sheet.css" TYPE="text/css"> </HEAD> <BODY> <CENTER> <TABLE BORDER=5> <TR><TH CLASS="TITLE"> Reusing JavaBeans in JSP</TABLE> </CENTER> <P> <jsp:usebean id="test" class="hall.simplebean" /> <jsp:setproperty name="test" property="message" value="hello WWW" /> <H1>Message: <I> <jsp:getproperty name="test" property="message" /> </I></H1> </BODY> </HTML> SimpleBean.java BeanTest jsp Bean

288 Java package hall; public class SimpleBean private String message = "No message specified"; public String getmessage() return(message); public void setmessage(string message) this.message = message; Java Bean package hall; public class SimpleBean private String message = "No message specified"; public String getmessage() return(message); public void setmessage(string message) this.message = message; package hall; public class SimpleBean private String message = "No message specified"; public String getmessage() return(message); public void setmessage(string message) this.message = message;

13 Java Server Pages 289 bean bean <jsp:usebean id="name" class="package.class" /> use jsp:setproperty and jsp:getproperty bean <jsp:usebean...> Body </jsp:usebean> bean Bean jsp:usebean id class scope, type beanname 13-2 13-2 jsp:usedbean id class scope type Bean id scope Bean bean Bean page, request, session, application page Bean PageContext request Bean ServletRequest session Bean HttpSession application Bean ServletContext id scope jsp:usebean jsp:usebean jsp:setparameter id beanname bean bean beanname type class (3) jsp:setproperty jsp:setproperty bean jsp:usebean <jsp:usebean id="myname"... /> <jsp:setproperty name="myname" property="someproperty"... /> jsp:setproperty bean jsp:usebean <jsp:usebean id="myname"... >... <jsp:setproperty name="myname" property="someproperty".../> </jsp:usebean> bean

290 Java jsp:setproperty 13-3 13-3 Name Property Value Bean jsp:usebean jsp:setproperty * bean name target wrapper value of numbers, boolean, Boolean, byte, Byte, char Character boolean true Boolean.valueOf 42 Integer.valueOf value param param Param null Bean numitems numberofitems <jsp:setproperty name="orderbean" property="numberofitems" param="numitems" /> param value Bean numdigits Bean numdigits numprimes JspPrimes.jsp <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE>Reusing JavaBeans in JSP</TITLE> <LINK REL=STYLESHEET HREF="My-Style-Sheet.css" TYPE="text/css"> </HEAD> <BODY> <CENTER> <TABLE BORDER=5> <TR><TH CLASS="TITLE"> Reusing JavaBeans in JSP</TABLE> </CENTER> <P> <jsp:usebean id="primetable" class="hall.numberedprimes" /> <jsp:setproperty name="primetable" property="numdigits" /> <jsp:setproperty name="primetable" property="numprimes" /> Some <jsp:getproperty name="primetable" property="numdigits" />

13 Java Server Pages 291 digit primes: <jsp:getproperty name="primetable" property="numberedlist" /> </BODY> </HTML (4) jsp:getproperty Bean name jsp:usebean bean property <jsp:usebean id="itembean"... />... <UL> <LI>Number of items: <jsp:getproperty name="itembean" property="numitems" /> <LI>Cost of each: <jsp:getproperty name="itembean" property="unitcost" /> </UL> (5) jsp:forward page <jsp:forward page="hello1.jsp" /> <jsp:forward page="<%= somejavaexpression %>" /> Hello5.jsp Hello5.jsp 13.6 Hello1.jsp 13.6 (6) jsp:plugin Java Java applet 13-4

292 Java 13-4 <%-- comment --%> jsp <!-- comment --> html jsp <\% <%. %\> %>. \' \" %\> %> <\% <% 13.3 JSP 1 <!-- Number Guess Game --> <%@ page import = "num.numberguessbean" %> // Java Bean <jsp:usebean id="numguess" class="num.numberguessbean" scope="session"/> // Bean ID <jsp:setproperty name="numguess" property="*"/> // Bean numguess <html> <head><title>number Guess</title></head> <body bgcolor="white"> <font size=4> <!----- <% if (numguess.getsuccess()) %> // Bean //GetSuccess // Congratulations! You got it.

13 Java Server Pages 293 And after just <%= numguess.getnumguesses() %> tries.<p> // Bean //getnumguesses <% numguess.reset(); %> // Bean Reset Care to <a href="numguess.jsp">try again</a>? // <% else if (numguess.getnumguesses() == 0) %> // Welcome to the Number Guess game.<p> I'm thinking of a number between 1 and 100.<p> <form method=get> // // Get What's your guess? <input type=text name=guess> // <input type=submit value="submit"> // </form> // <% else %> Good guess, but nope. Try <b><%= numguess.gethint() %></b>. // // Bean gethint() You have made <%= numguess.getnumguesses() %> guesses.<p> // Bean getnumguesses I'm thinking of a number between 1 and 100.<p> <form method=get> What's your guess? <input type=text name=guess> <input type=submit value="submit"> </form> // <% %> </font>

294 Java </body> </html> Bean // Number Guess Game package num; import java.util.*; public class NumberGuessBean int answer; boolean success; String hint; int numguesses; public NumberGuessBean() reset(); public void setguess(string guess) numguesses++; int g; try g = Integer.parseInt(guess); catch (NumberFormatException e) g = -1; if (g == answer) success = true; else if (g == -1) hint = "a number next time"; else if (g < answer) hint = "higher"; else if (g > answer)

13 Java Server Pages 295 hint = "lower"; public boolean getsuccess() return success; public String gethint() return "" + hint; public int getnumguesses() return numguesses; public void reset() answer = Math.abs(new Random().nextInt() % 100) + 1; success = false; numguesses = 0; 13.7~ 13.10 13.7 2 <html>

296 Java 13.8 13.9 13.10 75

13 Java Server Pages 297 <!-- --> <body bgcolor="white"> <jsp:usebean id='clock' scope='page' class='dates.jspcalendar' type="dates.jspcalendar" /> <font size=4> <ul> <li> Day of month: is <jsp:getproperty name="clock" property="dayofmonth"/> <li> Year: is <jsp:getproperty name="clock" property="year"/> <li> Month: is <jsp:getproperty name="clock" property="month"/> <li> Time: is <jsp:getproperty name="clock" property="time"/> <li> Date: is <jsp:getproperty name="clock" property="date"/> <li> Day: is <jsp:getproperty name="clock" property="day"/> <li> Day Of Year: is <jsp:getproperty name="clock" property="dayofyear"/> <li> Week Of Year: is <jsp:getproperty name="clock" property="weekofyear"/> <li> era: is <jsp:getproperty name="clock" property="era"/> <li> DST Offset: is <jsp:getproperty name="clock" property="dstoffset"/> <li> Zone Offset: is <jsp:getproperty name="clock" property="zoneoffset"/> </ul> </font> </body> </html> Bean package dates; import java.text.dateformat; import java.util.*; public class JspCalendar Calendar calendar = null; public JspCalendar() calendar = Calendar.getInstance(TimeZone.getTimeZone("PST")); Date trialtime = new Date(); calendar.settime(trialtime); public int getyear()

298 Java return calendar.get(calendar.year); public String getmonth() int m = getmonthint(); String[] months = new String [] "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ; if (m > 12) return "Unknown to Man"; return months[m - 1]; public String getday() int x = getdayofweek(); String[] days = new String[] "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"; if (x > 7) return "Unknown to Man"; return days[x - 1]; public int getmonthint() return 1 + calendar.get(calendar.month); public String getdate() return getmonthint() + "/" + getdayofmonth() + "/" + getyear(); public String gettime() return gethour() + ":" + getminute() + ":" + getsecond();

13 Java Server Pages 299 public int getdayofmonth() return calendar.get(calendar.day_of_month); public int getdayofyear() return calendar.get(calendar.day_of_year); public int getweekofyear() return calendar.get(calendar.week_of_year); public int getweekofmonth() return calendar.get(calendar.week_of_month); public int getdayofweek() return calendar.get(calendar.day_of_week); public int gethour() return calendar.get(calendar.hour_of_day); public int getminute() return calendar.get(calendar.minute); public int getsecond() return calendar.get(calendar.second); public static void main(string args[]) JspCalendar db = new JspCalendar(); p("date: " + db.getdayofmonth()); p("year: " + db.getyear()); p("month: " + db.getmonth()); p("time: " + db.gettime()); p("date: " + db.getdate());

300 Java p("day: " + db.getday()); p("dayofyear: " + db.getdayofyear()); p("weekofyear: " + db.getweekofyear()); p("era: " + db.getera()); p("ampm: " + db.getampm()); p("dst: " + db.getdstoffset()); p("zone Offset: " + db.getzoneoffset()); // p("timezone: " + db.getustimezone()); private static void p(string x) System.out.println(x); public int getera() return calendar.get(calendar.era); public String getustimezone() String[] zones = new String[] "Hawaii", "Alaskan", "Pacific", "Mountain", "Central", "Eastern"; int index = 10 + getzoneoffset(); if (index <= 5) return zones[10 + getzoneoffset()]; else return "Only US Time Zones supported"; public int getzoneoffset() return calendar.get(calendar.zone_offset)/(60*60*1000); public int getdstoffset() return calendar.get(calendar.dst_offset)/(60*60*1000); public int getampm()

13 Java Server Pages 301 return calendar.get(calendar.am_pm); 13.11 13.11 3 HTTP <html> <body bgcolor="white"> <h1> Request Information </h1> <font size="4"> JSP Request Method: <jsp:expr> request.getmethod() </jsp:expr> <br> Request URI: <jsp:expr> request.getrequesturi() </jsp:expr> <br> Request Protocol: <jsp:expr> request.getprotocol() </jsp:expr> <br> Servlet path: <jsp:expr> request.getservletpath() </jsp:expr> <br> Path info: <jsp:expr> request.getpathinfo() </jsp:expr> <br> Path translated: <jsp:expr> request.getpathtranslated() </jsp:expr>

302 Java <br> Query string: <jsp:expr> request.getquerystring() </jsp:expr> <br> Content length: <jsp:expr> request.getcontentlength() </jsp:expr> <br> Content type: <jsp:expr> request.getcontenttype() </jsp:expr> <br> Server name: <jsp:expr> request.getservername() </jsp:expr> <br> Server port: <jsp:expr> request.getserverport() </jsp:expr> <br> Remote user: <jsp:expr> request.getremoteuser() </jsp:expr> <br> Remote address: <jsp:expr> request.getremoteaddr() </jsp:expr> <br> Remote host: <jsp:expr> request.getremotehost() </jsp:expr> <br> Authorization scheme: <jsp:expr> request.getauthtype() </jsp:expr> <hr> The browser you are using is <jsp:expr> request.getheader("user-agent") </jsp:expr> <hr> </font> </body> </html> 13.12 13.12

13 Java Server Pages 303 4 <html> <body bgcolor="white"> <font size=5 color="red"> <%! String[] fruits; %> <jsp:usebean id="foo" scope="page" class="checkbox.checktest" /> <jsp:setproperty name="foo" property="fruit" param="fruit" /> <hr> The checked fruits (got using request) are: <br> <% fruits = request.getparametervalues("fruit"); %> <ul> <% if (fruits!= null) for (int i = 0; i < fruits.length; i++) %> <li> <% out.println (fruits[i]); else out.println ("none selected"); %> </ul> <br> <hr> The checked fruits (got using beans) are <br> <% fruits = foo.getfruit(); %> <ul> <% if (!fruits[0].equals("1")) for (int i = 0; i < fruits.length; i++) %> <li> <%

304 Java out.println (fruits[i]); else out.println ("none selected"); %> </ul> </font> </body> </html> Bean package checkbox; public class CheckTest String b[] = new String[] "1", "2", "3", "4" ; public String[] getfruit() return b; public void setfruit(string [] b) this.b = b; 13.13 13.14 13.13

13 Java Server Pages 305 13.14 5 <html> <jsp:usebean id="cb" scope="session" class="colors.colorgamebean" /> <jsp:setproperty name="cb" property="*" /> <% cb.processrequest(request); %> <body bgcolor=<%= cb.getcolor1() %>> <font size=6 color=<%= cb.getcolor2() %>> <p> <% if (cb.gethint()==true) %> <p> Hint #1: Vampires prey at night! <p> <p> Hint #2: Nancy without the n. <% %> <% if (cb.getsuccess()==true) %>

306 Java <p> CONGRATULATIONS!! <% if (cb.gethinttaken()==true) %> <p> ( although I know you cheated and peeked into the hints) <% %> <% %> <p> Total attempts so far: <%= cb.getattempts() %> <p> <p> <form method=post action=colrs.jsp> Color #1: <input type=text name= color1 size=16> <br> Color #2: <input type=text name= color2 size=16> <p> <input type=submit name=action value="submit"> <input type=submit name=action value="hint"> </form> </font> </body> </html> Bean package colors; import javax.servlet.http.*; public class ColorGameBean private String background = "yellow";

13 Java Server Pages 307 private String foreground = "red"; private String color1 = foreground; private String color2 = background; private String hint = "no"; private int attempts = 0; private int intval = 0; private boolean tookhints = false; public void processrequest(httpservletrequest request) // background = "yellow"; // foreground = "red"; if (! color1.equals(foreground)) if (color1.equalsignorecase("black") color1.equalsignorecase("cyan")) background = color1; if (! color2.equals(background)) if (color2.equalsignorecase("black") color2.equalsignorecase("cyan")) foreground = color2; attempts++; public void setcolor2(string x) color2 = x; public void setcolor1(string x) color1 = x; public void setaction(string x) if (!tookhints)

308 Java tookhints = x.equalsignorecase("hint"); hint = x; public String getcolor2() return background; public String getcolor1() return foreground; public int getattempts() return attempts; public boolean gethint() return hint.equalsignorecase("hint"); public boolean getsuccess() if (background.equalsignorecase("black") background.equalsignorecase("cyan")) if (foreground.equalsignorecase("black") foreground.equalsignorecase("cyan")) return true; else return false; return false; public boolean gethinttaken() return tookhints; public void reset() foreground = "red";

13 Java Server Pages 309 background = "yellow"; public void setintval(int value) intval = value; public int getintval() return intval; 13.15 13.16 13.15 13.16

310 Java 6 <HTML> <HEAD><TITLE> Calendar: A JSP APPLICATION </TITLE></HEAD> <BODY BGCOLOR="white"> <%@ page language="java" import="cal.*" %> <jsp:usebean id="table" scope="session" class="cal.tablebean" /> <% table.processrequest(request); if (table.getprocesserror() == false) %> <!-- html table goes here --> <CENTER> <TABLE WIDTH=60% BGCOLOR=yellow CELLPADDING=15> <TR> <TD ALIGN=CENTER> <A HREF=cal1.jsp?date=prev> prev </A> <TD ALIGN=CENTER> Calendar:<%= table.getdate() %></TD> <TD ALIGN=CENTER> <A HREF=cal1.jsp?date=next> next </A> </TR> </TABLE> <!-- the main table --> <TABLE WIDTH=60% BGCOLOR=lightblue BORDER=1 CELLPADDING=10> <TR> <TH> Time </TH> <TH> Appointment </TH> </TR> <FORM METHOD=POST ACTION=cal1.jsp> <% for(int i=0; i<table.getentries().getrows(); i++) cal.entry entr = table.getentries().getentry(i); %>

13 Java Server Pages 311 <TR> <TD> <A HREF=cal2.jsp?time=<%= entr.gethour() %>> <%= entr.gethour() %> </A> </TD> <TD BGCOLOR=<%= entr.getcolor() %>> <%= entr.getdescription() %> </TD> </TR> <% %> </FORM> </TABLE> <BR> <!-- footer --> <TABLE WIDTH=60% BGCOLOR=yellow CELLPADDING=15> <TR> <TD ALIGN=CENTER> <%= table.getname() %> : <%= table.getemail() %> </TD> </TR> </TABLE> </CENTER> <% else %> <font size=5> You must enter your name and email address correctly. </font> <% %> </BODY> </HTML> Bean package cal; import java.util.enumeration;

312 Java import java.util.hashtable; import javax.servlet.http.*; public class Entries private Hashtable entries; private static final String[] time = "8am", "9am", "10am", "11am", "12pm", "1pm", "2pm", "3pm", "4pm", "5pm", "6pm", "7pm", "8pm" ; public static final int rows = 12; public Entries () entries = new Hashtable (rows); for (int i=0; i < rows; i++) entries.put (time[i], new Entry(time[i])); public int getrows () return rows; public Entry getentry (int index) return (Entry)this.entries.get(time[index]); public int getindex (String tm) for (int i=0; i<rows; i++) if(tm.equals(time[i])) return i; return -1; public void processrequest (HttpServletRequest request, String tm) int index = getindex (tm); if (index >= 0) String descr = request.getparameter ("description"); ((Entry)entries.get(time[index])).setDescription (descr); package cal;

13 Java Server Pages 313 public class Entry String hour; String description; String color; public Entry (String hour) this.hour = hour; this.description = ""; public String gethour () return this.hour; public String getcolor () if (description.equals("")) return "lightblue"; else return "red"; public String getdescription () if (description.equals("")) return "None"; else return this.description; public void setdescription (String descr) description = descr; package cal; import java.text.dateformat; import java.util.*; public class JspCalendar Calendar calendar = null; Date currentdate;

314 Java public JspCalendar() calendar = Calendar.getInstance(); Date trialtime = new Date(); calendar.settime(trialtime); public int getyear() return calendar.get(calendar.year); public String getmonth() int m = getmonthint(); String[] months = new String [] "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ; if (m > 12) return "Unknown to Man"; return months[m - 1]; public String getday() int x = getdayofweek(); String[] days = new String[] "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"; if (x > 7) return "Unknown to Man"; return days[x - 1]; public int getmonthint() return 1 + calendar.get(calendar.month); public String getdate()

13 Java Server Pages 315 return getmonthint() + "/" + getdayofmonth() + "/" + getyear(); public String getcurrentdate() Date dt = new Date (); calendar.settime (dt); return getmonthint() + "/" + getdayofmonth() + "/" + getyear(); public String getnextdate() calendar.set (Calendar.DAY_OF_MONTH, getdayofmonth() + 1); return getdate (); public String getprevdate() calendar.set (Calendar.DAY_OF_MONTH, getdayofmonth() - 1); return getdate (); public String gettime() return gethour() + ":" + getminute() + ":" + getsecond(); public int getdayofmonth() return calendar.get(calendar.day_of_month); public int getdayofyear() return calendar.get(calendar.day_of_year); public int getweekofyear() return calendar.get(calendar.week_of_year); public int getweekofmonth() return calendar.get(calendar.week_of_month); public int getdayofweek()

316 Java return calendar.get(calendar.day_of_week); public int gethour() return calendar.get(calendar.hour_of_day); public int getminute() return calendar.get(calendar.minute); public int getsecond() return calendar.get(calendar.second); public int getera() return calendar.get(calendar.era); public String getustimezone() String[] zones = new String[] "Hawaii", "Alaskan", "Pacific", "Mountain", "Central", "Eastern"; int index = 10 + getzoneoffset(); if (index <= 5) return zones[10 + getzoneoffset()]; else return "Only US Time Zones are supported"; public int getzoneoffset() return calendar.get(calendar.zone_offset)/(60*60*1000); public int getdstoffset() return calendar.get(calendar.dst_offset)/(60*60*1000);

13 Java Server Pages 317 public int getampm() return calendar.get(calendar.am_pm); package cal; import java.beans.*; import javax.servlet.http.*; import javax.servlet.*; import java.util.hashtable; public class TableBean Hashtable table; JspCalendar JspCal; Entries entries; String date; String name = null; String email = null; boolean processerror = false; public TableBean () this.table = new Hashtable (10); this.jspcal = new JspCalendar (); this.date = JspCal.getCurrentDate (); public void setname (String nm) this.name = nm; public String getname () return this.name; public void setemail (String mail)

318 Java this.email = mail; public String getemail () return this.email; public String getdate () return this.date; public Entries getentries () return this.entries; public void processrequest (HttpServletRequest request) // Get the name and e-mail. this.processerror = false; if (name == null name.equals("")) setname(request.getparameter ("name")); if (email == null email.equals("")) setemail(request.getparameter ("email")); if (name == null email == null name.equals("") email.equals("")) this.processerror = true; return; // Get the date. String dater = request.getparameter ("date"); if (dater == null) date = JspCal.getCurrentDate (); else if (dater.equalsignorecase("next")) date = JspCal.getNextDate (); else if (dater.equalsignorecase("prev")) date = JspCal.getPrevDate (); entries = (Entries) table.get (date); if (entries == null) entries = new Entries (); table.put (date, entries); // If time is provided add the event.

13 Java Server Pages 319 String time = request.getparameter("time"); if (time!= null) entries.processrequest (request, time); public boolean getprocesserror () return this.processerror; 13.17~ 13.22 13.17 13.18

320 Java 13.19 8 00 13.20 7 Include JSP Include <html> <body bgcolor="white"> <font color="red">

13 Java Server Pages 321 13.21 13.22 <%@ page buffer="5" autoflush="false" %> <p>in place evaluation of another JSP which gives you the current time: <%@ include file="foo.jsp" %> <p> <jsp:include page="/jsp/include/foo.html" flush="true"/> by including the output of another JSP: <jsp:include page="foo.jsp" flush="true"/>

322 Java :-) </html> <body bgcolor="white"> <font color="red"> <%= System.currentTimeMillis() %> 13.23 13.23 8 Forward Forward <% double freemem = Runtime.getRuntime().freeMemory(); double totlmem = Runtime.getRuntime().totalMemory(); double percent = freemem/totlmem; if (percent < 0.5) %> <jsp:forward page="/jsp/forward/one.jsp"/> <% else %> <jsp:forward page="two.html"/> <% %> </html> <body bgcolor="white"> <font color="red"> VM Memory usage < 50%. </html> 13.24

13 Java Server Pages 323 13.24 50% 9 Plugin JSP Java Applet <title> Plugin example </title> <body bgcolor="white"> <h3> Current time is : </h3> <jsp:plugin type="applet" code="clock2.class" codebase="/examples/jsp/plugin/applet" jreversion="1.2" width="160" height="150" > <jsp:fallback> Plugin tag OBJECT or EMBED not supported by browser. </jsp:fallback> </jsp:plugin> <p> <h4> <font color=red> The above applet is loaded using the Java Plugin from a jsp page using the plugin tag. </font> </h4> </body> </html> Applet import java.util.*; import java.awt.*; import java.applet.*; import java.text.*; /**

324 Java * Time! * */ public class Clock2 extends Applet implements Runnable Thread timer; // The thread that displays clock int lastxs, lastys, lastxm, lastym, lastxh, lastyh; // Dimensions used to draw hands SimpleDateFormat formatter; // Formats the date displayed String lastdate; // String to hold date displayed Font clockfacefont; // Font for number display on clock Date currentdate; // Used to get date to display Color handcolor; // Color of main hands and dial Color numbercolor; // Color of second hand and numbers public void init() int x,y; lastxs = lastys = lastxm = lastym = lastxh = lastyh = 0; formatter = new SimpleDateFormat ("EEE MMM dd hh:mm:ss yyyy", Locale.getDefault()); currentdate = new Date(); lastdate = formatter.format(currentdate); clockfacefont = new Font("Serif", Font.PLAIN, 14); handcolor = Color.blue; numbercolor = Color.darkGray; try setbackground(new Color(Integer.parseInt(getParameter("bgcolor"),16))); catch (Exception E) try handcolor = new Color(Integer.parseInt(getParameter("fgcolor1"),16)); catch (Exception E) try numbercolor = new Color(Integer.parseInt(getParameter("fgcolor2"),16)); catch (Exception E) resize(300,300); // Set clock window size // Plotpoints allows calculation to only cover 45 degrees of the circle, // and then mirror

13 Java Server Pages 325 public void plotpoints(int x0, int y0, int x, int y, Graphics g) g.drawline(x0+x,y0+y,x0+x,y0+y); g.drawline(x0+y,y0+x,x0+y,y0+x); g.drawline(x0+y,y0-x,x0+y,y0-x); g.drawline(x0+x,y0-y,x0+x,y0-y); g.drawline(x0-x,y0-y,x0-x,y0-y); g.drawline(x0-y,y0-x,x0-y,y0-x); g.drawline(x0-y,y0+x,x0-y,y0+x); g.drawline(x0-x,y0+y,x0-x,y0+y); // Circle is just Bresenham's algorithm for a scan converted circle public void circle(int x0, int y0, int r, Graphics g) int x,y; float d; x=0; y=r; d=5/4-r; plotpoints(x0,y0,x,y,g); while (y>x) if (d<0) d=d+2*x+3; x++; else d=d+2*(x-y)+5; x++; y--; plotpoints(x0,y0,x,y,g); // Paint is the main part of the program public void paint(graphics g) int xh, yh, xm, ym, xs, ys, s = 0, m = 10, h = 10, xcenter, ycenter; String today; currentdate = new Date();

326 Java SimpleDateFormat formatter = new SimpleDateFormat("s",Locale.getDefault()); try s = Integer.parseInt(formatter.format(currentDate)); catch (NumberFormatException n) s = 0; formatter.applypattern("m"); try m = Integer.parseInt(formatter.format(currentDate)); catch (NumberFormatException n) m = 10; formatter.applypattern("h"); try h = Integer.parseInt(formatter.format(currentDate)); catch (NumberFormatException n) h = 10; formatter.applypattern("eee MMM dd HH:mm:ss yyyy"); today = formatter.format(currentdate); xcenter=80; ycenter=55; // a= s* pi/2 - pi/2 (to switch 0,0 from 3:00 to 12:00) // x = r(cos a) + xcenter, y = r(sin a) + ycenter xs = (int)(math.cos(s * 3.14f/30-3.14f/2) * 45 + xcenter); ys = (int)(math.sin(s * 3.14f/30-3.14f/2) * 45 + ycenter); xm = (int)(math.cos(m * 3.14f/30-3.14f/2) * 40 + xcenter); ym = (int)(math.sin(m * 3.14f/30-3.14f/2) * 40 + ycenter); xh = (int)(math.cos((h*30 + m/2) * 3.14f/180-3.14f/2) * 30 + xcenter); yh = (int)(math.sin((h*30 + m/2) * 3.14f/180-3.14f/2) * 30 + ycenter); // Draw the circle and numbers g.setfont(clockfacefont); g.setcolor(handcolor); circle(xcenter,ycenter,50,g); g.setcolor(numbercolor); g.drawstring("9",xcenter-45,ycenter+3);

13 Java Server Pages 327 g.drawstring("3",xcenter+40,ycenter+3); g.drawstring("12",xcenter-5,ycenter-37); g.drawstring("6",xcenter-3,ycenter+45); // Erase if necessary, and redraw g.setcolor(getbackground()); if (xs!= lastxs ys!= lastys) g.drawline(xcenter, ycenter, lastxs, lastys); g.drawstring(lastdate, 5, 125); if (xm!= lastxm ym!= lastym) g.drawline(xcenter, ycenter-1, lastxm, lastym); g.drawline(xcenter-1, ycenter, lastxm, lastym); if (xh!= lastxh yh!= lastyh) g.drawline(xcenter, ycenter-1, lastxh, lastyh); g.drawline(xcenter-1, ycenter, lastxh, lastyh); g.setcolor(numbercolor); g.drawstring("", 5, 125); g.drawstring(today, 5, 125); g.drawline(xcenter, ycenter, xs, ys); g.setcolor(handcolor); g.drawline(xcenter, ycenter-1, xm, ym); g.drawline(xcenter-1, ycenter, xm, ym); g.drawline(xcenter, ycenter-1, xh, yh); g.drawline(xcenter-1, ycenter, xh, yh); lastxs=xs; lastys=ys; lastxm=xm; lastym=ym; lastxh=xh; lastyh=yh; lastdate = today; currentdate=null; public void start() timer = new Thread(this); timer.start(); public void stop() timer = null;

328 Java public void run() Thread me = Thread.currentThread(); while (timer == me) try Thread.currentThread().sleep(100); catch (InterruptedException e) repaint(); public void update(graphics g) paint(g); public String getappletinfo() return "Title: A Clock \nauthor: Rachel Gollub, 1995 \nan analog clock."; public String[][] getparameterinfo() String[][] info = "bgcolor", "hexadecimal RGB number", "The background color. Default is the color of your browser.", "fgcolor1", "hexadecimal RGB number", "The color of the hands and dial. Default is blue.", "fgcolor2", "hexadecimal RGB number", "The color of the seconds hand and numbers. Default is dark gray." ; return info; 13.25 10 JSP Servlet JSP Servlet JSP <body bgcolor="white"> <!-- Forward to a servlet -->

13 Java Server Pages 329 13.25 Applet <jsp:forward page="/servlet/servlettojsp" /> </html> Servlet import javax.servlet.*; import javax.servlet.http.*; public class servlettojsp extends HttpServlet public void doget (HttpServletRequest request, HttpServletResponse response) try // Set the attribute and Forward to hello.jsp request.setattribute ("servletname", "servlettojsp"); getservletconfig().getservletcontext().getrequestdispatcher("/jsp/jsptoserv/hello.jsp").forward (request, response); catch (Exception ex) ex.printstacktrace ();

330 Java 13.26 13.26 JSP Servlet 13.4 JSP JDBC JDBC JSP JDBC JSP JSP JSP JDBC DRIVER JDBC-ODBC Windows 98 JDBC-ODBC Servlet JSP <html> <head> <title>jsp JDBC</title> </head> <body text=blue> <%@ page contenttype="text/html;charset=gb2312"%> <% // java.sql.connection sqlcon; // java.sql.statement sqlstmt; //SQL

java.sql.resultset sqlrst; // 13 Java Server Pages 331 java.lang.string strcon; // java.lang.string strsql; //SQL Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // strcon = "jdbc:odbc:test_db"; // sqlcon = java.sql.drivermanager.getconnection(strcon,"sa",""); // SQL sqlstmt = sqlcon.createstatement(); // strsql = "select * from TITLES"; sqlrst = sqlstmt.executequery(strsql); // SQL while(sqlrst.next()) for(int i=1;i<11;i++) %> <%=i%> <%=sqlrst.getstring(i)%><br> <% // sqlrst.close(); // SQL

332 Java sqlstmt.close(); // sqlcon.close(); %> </body> </html> TITLES 1389 19.9900 5000.0000 10 4095 An overview of available database systems with emphasis on common business applications. Illustrated. 1991-06-12 00:00:00.000 BU1046 The Busy Executive Database Guide women 1389 18.9900 5000.0000 10 4095 An overview of available database systems with 1900-03-15 00:00:00.000 BU1111 Cooking with Computers: Surreptitious Balance Sheets business 1389 11.9500 5000.0000 10 3876 Helpful hints on how to use your electronic resources to the best advantage. 1991-06-09 00:00:00.000 BU2075 You Can Combat Computer Stress! business 0736 2.9900 10125.0000 24 18722 The latest medical and psychological techniques for living 13.5 1 JSP ASP ASP JSP Windows Windows NT ASP JSP ASP 2 JSP Servlet JSP ASCII Servlet Servlet 3 Java Bean COM JavaBean COM COM Windows JavaBean

14 JDBC API Java JSP Servlet JDBC JDBC API Servlet,JSP 14.1 Class DriverManager 1 public class DriverManager extends Object JDBC 2 static void deregisterdriver(driver driver) static Connection getconnection(string url) static Connection getconnection(string url, Properties info) static Connection getconnection(string url, String user, String password) static Driver getdriver(string url) static Enumeration getdrivers() static int getlogintimeout() static PrintStream getlogstream() static PrintWriter getlogwriter() static void println(string message) static void registerdriver(driver driver) static void setlogintimeout(int seconds) static void setlogstream(printstream out) static void setlogwriter(printwriter out) void deregisterdriver public

334 Java Driver throws SQLException Applet GetConnection public Connection String throws SQLException getconnection public Connection String Property throws SQLException Property getconnection public Connection String String String throws SQLException GetDriver public Driver String throws SQLException getdrivers

14 JDBC API 335 public Enumeration throws SQLException setlogintimeout public throws SQLException getlogintimeout public throws SQLException setlogstream public PrintStream throws SQLException getlogstream public PrintStream throws SQLException println

336 Java public String throws SQLException 14.2 Interface Driver 1 public abstract interface Driver 2 boolean acceptsurl(string url) Connection connect(string url, Properties info) int getmajorversion() int getminorversion() DriverPropertyInfo[] getpropertyinfo(string url, Properties info) boolean jdbccompliant() connect public Connection String Properties throws SQLException acceptsurl public String throws SQLException

14 JDBC API 337 getpropertyinfo public DriverPropertyInfo String Properties throws SQLException getmajorversion public throws SQLException getminorversion public throws SQLException jdbccompliant public throws SQLException JDBC COMPLIANT 14.3 Class DriverPropertyInfo 1 public class DriverPropertyInfo extends Object

338 Java 2 String[] choices String description String name boolean required String value name public String description public String NULL required public true null false Value public String Choices public String 3 DriverPropertyInfo public String String DriverPropertyInfo

14 JDBC API 339 14.4 Interface Connection 1 public abstract interface Connection 2 void clearwarnings() void close() void commit() Statement createstatement() Statement createstatement(int resultsettype, int resultsetconcurrency) boolean getautocommit() String getcatalog() DatabaseMetaData getmetadata() int gettransactionisolation() Map gettypemap() SQLWarning getwarnings() boolean isclosed() boolean isreadonly() String nativesql(string sql) CallableStatement preparecall(string sql) CallableStatement preparecall(string sql, int resultsettype, int resultsetconcurrency) PreparedStatement preparestatement(string sql) PreparedStatement preparestatement(string sql, int resultsettype, int resultsetconcurrency) void rollback() void setautocommit(boolean autocommit) void setcatalog(string catalog) void setreadonly(boolean readonly) void settransactionisolation(int level) void settypemap(map map) createstatement public Statement

340 Java throws SQLException Statement preparestatement public PreparedStatement String throws SQLException PreparedStatement preparecall public CallableStatement String throws SQLException CallableStatement nativesql public String throws SQLException SQL SQL setautocommit public throws SQLException getautocommit public

throws SQLException commit public throws SQLException rollback public throws SQLException close public throws SQLException Connection isclosed public throws SQLException getmetadata public DatabaseMetaData 14 JDBC API 341

342 Java throws SQLException DatabaseMetaData setreadonly public throws SQLException isreadonly public throws SQLException setcatalog public String throws SQLException getcatalog public String Catalog throws SQLException settransactionisolation public

throws SQLException gettransactionisolation public throws SQLException 14 JDBC API 343 getwarnings public SQLWarning throws SQLException SQL Warning clearwarnings public throws SQLException SQL Warning createstatement public Statement String Result String Currency throws SQLException Statement ResultSet Currency PrepareStatement public PreparedStatement

344 Java String String Result String Currency throws SQLException PreparedStatement ResultSet Currency PrepareCall public CallableStatement String String Result String Currency throws SQLException CallableStatement ResultSet Currency GetTypeMap public Map throws SQLException Map settypemap public Map throws SQLException Map 14.5 Interface PreparedStatement 1 public abstract interface PreparedStatement extends Statement void addbatch()

14 JDBC API 345 void clearparameters() boolean execute() ResultSet executequery() int executeupdate() ResultSetMetaData getmetadata() void setarray(int i, Array x) void setasciistream(int parameterindex, InputStream x, int length) void setbigdecimal(int parameterindex, BigDecimal x) void setbinarystream(int parameterindex, InputStream x, int length) void setblob(int i, Blob x) void setboolean(int parameterindex, boolean x) void setbyte(int parameterindex, byte x) void setbytes(int parameterindex, byte[] x) void setcharacterstream(int parameterindex, Reader reader, int length) void setclob(int i, Clob x) void setdate(int parameterindex, Date x) void setdate(int parameterindex, Date x, Calendar cal) void setdouble(int parameterindex, double x) void setfloat(int parameterindex, float x) void setint(int parameterindex, int x) void setlong(int parameterindex, long x) void setnull(int parameterindex, int sqltype) void setnull(int paramindex, int sqltype, String typename) void setobject(int parameterindex, Object x) void setobject(int parameterindex, Object x, int targetsqltype) void setobject(int parameterindex, Object x, int targetsqltype, int scale) void setref(int i, Ref x) void setshort(int parameterindex, short x) void setstring(int parameterindex, String x) void settime(int parameterindex, Time x) void settime(int parameterindex, Time x, Calendar cal) void settimestamp(int parameterindex, Timestamp x) void settimestamp(int parameterindex, Timestamp x, Calendar cal) void setunicodestream(int parameterindex, InputStream x, int length) executequery public ResultSet String SQL

346 Java throws SQLException executeupdate public String SQL throws SQLException setnull public int int SQL TYPE throws SQLException null setboolean public int throws SQLException setbyte public int Byte throws SQLException Byte setshort public int Short

14 JDBC API 347 throws SQLException Short setint public int Int throws SQLException Int setlong public int Long throws SQLException Long setfloat public int Float throws SQLException Float setdouble public int Double throws SQLException Double setbigdecimal public int BigDecimal

348 Java throws SQLException BigDecimal setstring public int String throws SQLException String setbytes public int Byte throws SQLException Byte setdate public int Date throws SQLException Date settime public int Time throws SQLException Time settimestamp public int Timestamp

14 JDBC API 349 throws SQLException Timestamp setasciistream public int InputStream Int throws SQLException setunicodestream public int InputStream Int throws SQLException Unicode setbianrystream public int InputStream Int throws SQLException Binary clearparameters public throws SQLException setobject public int Object Int SqlType Int

350 Java throws SQLException Object setobject public int Object Int SqlType throws SQLException Object 0 setobject public int Object throws SQLException Object SQL TYPE 0 execute public throws SQLException addbatch public throws SQLException setcharacterstream public int Reader Int

14 JDBC API 351 throws SQLException setref public int Ref throws SQLException Ref setblob public int Blob throws SQLException Blob setclob public int Clob throws SQLException Clob setarray public int Array throws SQLException Array getmetadata public ResultSetMetaData

352 Java throws SQLException ResultSetMetaData setdate public int Date Callender throws SQLException Date Callender Driver settime public int Time Callender throws SQLException Time Callender Driver settimestamp public int Timestamp Callender throws SQLException Timestamp Callender Driver SetNull public sqltype String throws SQLException null 14.6 Interface ResultSet 1

public abstract interface ResultSet 2 static int CONCUR_READ_ONLY static int CONCUR_UPDATABLE static int FETCH_FORWARD static int FETCH_REVERSE static int FETCH_UNKNOWN static int TYPE_FORWARD_ONLY static int TYPE_SCROLL_INSENSITIVE static int TYPE_SCROLL_SENSITIVE FETCH_FORWARD public static final FETCH_REVERSE public static final FETCH_UNKNOWN public static final TYPE_FORWARD_ONLY public static final 14 JDBC API 353 TYPE_SCROLL_INSENSITIVE public static final TYPE_SCROLL_SENSITIVE public static final CONCUR_READ_ONLY public static final

354 Java CONCUR_UPDATABLE public static final 3 boolean absolute(int row) void afterlast() void beforefirst() void cancelrowupdates() void clearwarnings() void close() void deleterow() int findcolumn(string columnname) boolean first() Array getarray(int i) Array getarray(string colname) InputStream getasciistream(int columnindex) InputStream getasciistream(string columnname) BigDecimal getbigdecimal(int columnindex) BigDecimal getbigdecimal(int columnindex, int scale) BigDecimal getbigdecimal(string columnname) BigDecimal getbigdecimal(string columnname, int scale) InputStream getbinarystream(int columnindex) InputStream getbinarystream(string columnname) Blob getblob(int i) Blob getblob(string colname) boolean getboolean(int columnindex) boolean getboolean(string columnname) byte getbyte(int columnindex) byte getbyte(string columnname) byte[] getbytes(int columnindex) byte[] getbytes(string columnname) Reader getcharacterstream(int columnindex) Reader getcharacterstream(string columnname) Clob getclob(int i) Clob getclob(string colname) int getconcurrency()

14 JDBC API 355 String getcursorname() Date getdate(int columnindex) Date getdate(int columnindex, Calendar cal) Date getdate(string columnname) Date getdate(string columnname, Calendar cal) double getdouble(int columnindex) double getdouble(string columnname) int getfetchdirection() int getfetchsize() float getfloat(int columnindex) float getfloat(string columnname) int getint(int columnindex) int getint(string columnname) long getlong(int columnindex) long getlong(string columnname) ResultSetMetaData getmetadata() Object getobject(int columnindex) Object getobject(int i, Map map) Object getobject(string columnname) Object getobject(string colname, Map map) Ref getref(int i) Ref getref(string colname) int getrow() short getshort(int columnindex) short getshort(string columnname) Statement getstatement() String getstring(int columnindex) String getstring(string columnname) Time gettime(int columnindex) Time gettime(int columnindex, Calendar cal) Time gettime(string columnname) Time gettime(string columnname, Calendar cal) Timestamp gettimestamp(int columnindex) Timestamp gettimestamp(int columnindex, Calendar cal) Timestamp gettimestamp(string columnname) Timestamp gettimestamp(string columnname, Calendar cal) int gettype() InputStream getunicodestream(int columnindex) InputStream getunicodestream(string columnname) SQLWarning getwarnings()

356 Java void insertrow() boolean isafterlast() boolean isbeforefirst() boolean isfirst() boolean islast() boolean last() void movetocurrentrow() void movetoinsertrow() boolean next() boolean previous() void refreshrow() boolean relative(int rows) boolean rowdeleted() boolean rowinserted() boolean rowupdated() void setfetchdirection(int direction) void setfetchsize(int rows) void updateasciistream(int columnindex, InputStream x, int length) void updateasciistream(string columnname, InputStream x, int length) void updatebigdecimal(int columnindex, BigDecimal x) void updatebigdecimal(string columnname, BigDecimal x) void updatebinarystream(int columnindex, InputStream x, int length) void updatebinarystream(string columnname, InputStream x, int length) void updateboolean(int columnindex, boolean x) void updateboolean(string columnname, boolean x) void updatebyte(int columnindex, byte x) void updatebyte(string columnname, byte x) void updatebytes(int columnindex, byte[] x) void updatebytes(string columnname, byte[] x) void updatecharacterstream(int columnindex, Reader x, int length) void updatecharacterstream(string columnname, Reader reader, int length) void updatedate(int columnindex, Date x) void updatedate(string columnname, Date x) void updatedouble(int columnindex, double x) void updatedouble(string columnname, double x) void updatefloat(int columnindex, float x) void updatefloat(string columnname, float x) void updateint(int columnindex, int x) void updateint(string columnname, int x) void updatelong(int columnindex, long x)

void updatelong(string columnname, long x) void updatenull(int columnindex) void updatenull(string columnname) void updateobject(int columnindex, Object x) void updateobject(int columnindex, Object x, int scale) void updateobject(string columnname, Object x) void updateobject(string columnname, Object x, int scale) void updaterow() void updateshort(int columnindex, short x) void updateshort(string columnname, short x) void updatestring(int columnindex, String x) void updatestring(string columnname, String x) void updatetime(int columnindex, Time x) void updatetime(string columnname, Time x) void updatetimestamp(int columnindex, Timestamp x) void updatetimestamp(string columnname, Timestamp x) boolean wasnull() next public throws SQLException close public throws SQLException wasnull public throws SQLException 14 JDBC API 357

358 Java null getstring public String throws SQLException getboolean public throws SQLException getbyte public Byte throws SQLException Byte getshort public short throws SQLException Short getint public Int throws SQLException

Int getlong public Long throws SQLException Long getfloat public Float throws SQLException Float getdouble public Double throws SQLException Double getdecimal public Bigdecimal throws SQLException BigDecimal getbytes public byte throws SQLException 14 JDBC API 359

360 Java Byte getdate public Date throws SQLException Date gettime public Time throws SQLException Time gettimestamp public TimeStamp throws SQLException TimeStamp getasciistream public InputStream throws SQLException getunicodestream public InputStream throws SQLException

Unicode getbinarystream public InputStream throws SQLException getstring public String String throws SQLException String getboolean public Boolean String throws SQLException Bool getbyte public Byte String throws SQLException Byte getshort public Short Short throws SQLException 14 JDBC API 361

362 Java Short getint public Int String throws SQLException Int getlong public Long String throws SQLException Long getfloat public Float String throws SQLException Float getdouble public Double String throws SQLException Double getbigdecimal public BigDecimal String throws SQLException

BigDecimal getbytes public Byte String throws SQLException Byte getdate public Date String throws SQLException Date gettime public Time String throws SQLException Time gettimestamp public TimeStamp String throws SQLException Timestamp getasciistream public String throws SQLException 14 JDBC API 363

364 Java getunicodestream public String throws SQLException Unicode getbinarystream public String throws SQLException getwarnings public SQLWarning throws SQLException SQLWarning clearwarnings public throws SQLException SQLWarnings getcursorname public String throws SQLException

14 JDBC API 365 getmetadata public ResultSetMetaData throws SQLException ResultSetMetaData getobject public Object Int throws SQLException Object getobject public Object String throws SQLException Object FindColumn public String throws SQLException getcharacterstream public Reader throws SQLException

366 Java getcharacterstream public Reader String throws SQLException IsBeforeFirst public throws SQLException isafterlast public throws SQLException isfirst public throws SQLException islast public throws SQLException

beforefirst public throws SQLException afterlast public throws SQLException first public throws SQLException last public throws SQLException getrow public throws SQLException 14 JDBC API 367

368 Java absolute public throws SQLException relative public throws SQLException previous public throws SQLException setfetchdirection public throws SQLException getfetchdirection public throws SQLException

setfetchsize public throws SQLException 14 JDBC API 369 getfetchsize public throws SQLException gettype public throws SQLException TYPE_FORWARD_ONLY, TYPE_SCROLL_INSENSITIVE, or TYPE_SCROLL_SENSITIVE getconcurrency public throws SQLException Corrency CONCUR_READ_ONLY or CONCUR_UPDATABLE