Sunteți pe pagina 1din 88

Module 2: JavaScript

The lessons covered in this module include: DHTML Introduction to JavaScript Elements of JavaScript Program JavaScript Statements Functions Objects Defining Objects Arrays Events Time Outs Integrating JavaScript with Java Creating Windows Summary Examples and Exercises
Version 1.1

Objectives
At the end of this module you will be able to: 1. Write JavaScript code using all the basic elements of JavaScript Programs 2. Create Windows & Dialog Boxes 3. Use the JavaScripts in-built objects in a web page 4. Write code that does Event Handling in HTML pages 5. Manipulate HTML Forms through JavaScript dynamically 6. Integrate Java and JavaScript through Applets

Version 1.1

DHTML
DHTML stands for Dynamic Hyper Text Markup Language which helps to add Dynamic content to static HTML pages.

Version 1.1

Introduction to JavaScript
JavaScript is: 1. An easy to use object scripting language 2. Designed for creating live online applications 3. Code is included as part of a HTML document 4. Scripts are run by the Web browser

Version 1.1

Introduction to JavaScript: JavaScript Versus Java


1. JavaScript can be combined directly with HTML 2. The JavaScript language structure is simpler than that of Java 3. JavaScript is a purely interpreted language 4. The JavaScript interpreter is built into a Web browser

Version 1.1

Introduction to JavaScript: Using the SCRIPT Tag


<HTML> <HEAD> <TITLE>Simple JavaScript Example </TITLE> </HEAD> <BODY> HTML Text goes here. <SCRIPT LANGUAGE="JavaScript"> document.write("Here is my output.") </SCRIPT> </BODY> </HTML>

Version 1.1

Elements of JavaScript Program


Elements of JavaScript Program can be divided into five categories, as follows: 1. Variables 2. Expressions 3. Control Structures 4. Functions 5. Objects and Arrays

Version 1.1

Elements of JavaScript Program: Variables


Data Types Rules for variable names Type Casting Variable Declaration and Scope

Version 1.1

Version 1.1

JavaScript Statements
Conditional statements: if...else and switch Loop Statements: for, while, dowhile, break and continue Object Manipulation Statements and Operators: for...in, new, this and with Comments: single-line (//) and multi-line (/*...*/)

Version 1.1

10

JavaScript Statements: switch Statement


A switch statement allows a program to evaluate an expression and attempt to match the expression's value to a case label. If a match is found, the program executes the associated statement. A switch statement looks as follows: switch (expression){ case label : statement; break; default : statement; }

Version 1.1

11

JavaScript Statements: for Statement


A for loop repeats until a specified condition evaluates to false. A for statement looks as follows:
for ([initial-expression]; [condition]; [increment-expression]) { statements }

Version 1.1

12

JavaScript Statements: dowhile Statement


The do...while statement repeats until a specified condition evaluates to false. A do...while statement looks as follows:
do { statement } while (condition)

Version 1.1

13

JavaScript Statements: while Statement


A while statement executes its statements as long as a specified condition evaluates to true. A while statement looks as follows:
while (condition) { statements }

Version 1.1

14

Functions
Functions are one of the fundamental building blocks in JavaScript. A function is a JavaScript procedure: a set of statements that performs a specific task. To use a function, you must first define it, then your script can call it. A function definition looks as follows:
function gcd(m,n) { return n > 0 }

? gcd(n,m%n) : m ;

Version 1.1

15

Objects
An object is a self-contained unit of code having the following characteristics:

Properties Methods Identity

Version 1.1

16

Objects: The Window Object


At the top of the browser hierarchy is the window object, which represents a browser window The properties/methods of this object are:

status alert() confirm() prompt()

Version 1.1

17

Objects: The Document Object


Represents characteristics of the current HTML page. Some of its properties are:

title fgColor

- lastModified - bgColor

Some of its methods are: write() writeln() In the browser object hierarchy, the document object is contained in a window object (for a page without frames)

Version 1.1

18

Objects: The Form Object


Represents an HTML Form. Has the same name as the NAME attribute in the FORM tag In the browser object hierarchy, the form object is contained in the document object

Version 1.1

19

Objects: Frame Objects


Each Frame in a frame set is represented as a frame object A frame set contains an array of frame objects representing all the frames in it You can refer to a particular frame :

By name - if it has one By reference to the parent and the array index of that frame

Version 1.1

20

Objects: The Math Object


The Math object cant be created, since it exists automatically in all Java Script Programs Its properties represent mathematical constants Its methods are mathematical functions

Version 1.1

21

Objects: The String Object


Any String variable in JavaScript is a String object. It has a property

Length and Many Methods

Version 1.1

22

Objects: The Date Object


Is built-in JavaScript object Create using new keyword

Version 1.1

23

Version 1.1

24

Arrays
JavaScript doesnt support array variables Arrays need to be created using array object

Version 1.1

25

Events
Are things that happen to the browser Used to trigger portions of program Pertain to the web page containing the script

Version 1.1

26

Events: Event Handlers


Embedded in HTML tags as part of anchor and links or any of the form element tags.

Version 1.1

27

Time Outs
Statements that will be executed after a certain amount of time elapses Handy for periodically updating a Web Page or for delaying the display of a message or execution of a function

Version 1.1

28

Version 1.1

29

Summary
In this module you have learnt to: Write JavaScript code using all the basic elements of JavaScript Programs Create Windows & Dialog Boxes Use the JavaScripts in-built objects in a web page Write code that does Event Handling in HTML pages Manipulate HTML Forms through JavaScript dynamically Integrate Java and JavaScript through Applets

Version 1.1

30

Version 1.1

31

Version 1.1

32

Version 1.1

33

Version 1.1

34

Version 1.1

35

Version 1.1

36

Version 1.1

37

Version 1.1

38

Version 1.1

39

Version 1.1

40

Version 1.1

41

Version 1.1

42

Version 1.1

43

Version 1.1

44

Module 3: JDBC
The lessons covered in this module include: Introduction to JDBC Architecture & Querying with JDBC Stage 1: Connect Stage 2: Query Stage 3: Process the Results Stage 4: Close The DatabaseMetaData Object The ResultSetMetaData Object Mapping Database Types to Java Types The PreparedStatement Object The CallableStatement Object Using Transactions Summary of JDBC Classes Summary Examples

Version 1.1

45

Objectives
At the end of this module you will be able to: Connect to a database using Java Database Connectivity (JDBC) Create and execute a query using JDBC Invoke prepared statements Commit and roll back transactions Use the Metadata objects to retrieve more information about the database or the resultset

Version 1.1

46

Introduction to JDBC
JDBC is a standard interface for connecting to relational databases from Java The JDBC classes and interfaces are in the java.sql package

Version 1.1

47

Architecture & Querying with JDBC

Connect

Query

Process results

Close

Version 1.1

48

Stage 1: Connect

Connect

Register the driver

Query

Connect to the database

Process results

Close

Version 1.1

49

Connect: A JDBC Driver


Is an interpreter that translates JDBC method calls to vendorspecific database commands

JDBC calls

Driver

Database commands Database

Implements interfaces in java.sql Can also provide a vendors extensions to the JDBC standard

Version 1.1

50

JDBC Driver (Contd.).

JDBC-ODBC Bridge Driver (Type I Driver)

Version 1.1

51

JDBC Driver (Contd.).


Native JDBC Driver (Type II Driver)

Version 1.1

52

JDBC Drivers (Contd.).


All Java JDBC Net Drivers (Type III Driver)

Version 1.1

53

JDBC Drivers (Contd.).


Native Protocol All Java Drivers (Type IV Driver)

Version 1.1

54

Connect: About JDBC URL


JDBC uses a URL to identify the database connection.

jdbc:<subprotocol>:<subname>
Protocol Subprotocol Database identifier

jdbc:oracle:<driver>:@<database>
Version 1.1

55

JDBC URLs: Examples

JDBC-ODBC driver
jdbc:odbc:jdbcoodbcDriverDsn

OCI driver
jdbc:oracle:oci8:@<TNSNAMES entry>

Version 1.1

56

How to make the Connection?


1. Register the driver Class c = Class.forName( "oracle.jdbc.driver.OracleDriver"); Class c = Class.forName( sun.jdbc.odbc.JdbcOdbcDriver");

2. Connect to the database


Connection conn = DriverManager.getConnection(URL,userid,password); Connection conn = DriverManager.getConnection ("jdbc:oracle:thin:@myhost:1521:orcl", "scott", "tiger");
Version 1.1

57

Stage 2: Query

Connect

Query

Create a statement

Process results

Query the database

Close

Version 1.1

58

Query: The Statement Object


A Statement object sends your SQL statement to the database You need an active connection to create a JDBC statement Statement has three methods to execute a SQL statement:

executeQuery() for QUERY statements executeUpdate()for INSERT, UPDATE, DELETE, or DDL statements execute() for either type of statement

Version 1.1

59

How to Query the Database?

1.

Create an empty statement object

Statement stmt = conn.createStatement();

2. Execute the statement

ResultSet rset = stmt.executeQuery(statement); int count = stmt.executeUpdate(statement); boolean isquery = stmt.execute(statement);

Version 1.1

60

Querying the Database: Examples

Execute a select statement


Statement stmt = conn.createStatement(); ResultSet rset = stmt.executeQuery ("select NAME, VERTICAL from STUDENT");

Execute a delete statement


Statement stmt = conn.createStatement(); int rowcount = stmt.executeUpdate ("delete from STUDENT where ID = 1000");

Version 1.1

61

Stage 3: Process the Results

Connect

Query Step through the results

Process results

Assign results to Java variables

Close

Version 1.1

62

Process the Results: The ResultSet Object


JDBC returns the results of a query in a ResultSet object A ResultSet maintains a cursor pointing to its current row of data Use next() to step through the result set row by row getString(), getInt(), and so on assign each value to a Java variable

Version 1.1

63

How to Process the Result?


1. Step through the result set
while (rset.next()) { }

2. Use getXXX() to get each column value


String val = rset.getString(colname); String val = rset.getString(colIndex);

while (rset.next()) { String name = rset.getString(NAME"); String supervisor = rset.getString(SUPERVISOR"); // Process or display the data }

Version 1.1

64

How to handle SQL Null values?


Java primitive types cannot have null values Do not use a primitive type when your query might return a SQL null Use ResultSet.wasNull() to determine whether a column has a null value
while (rset.next()) { String year = rset.getString("YEAR"); if (rset.wasNull() { // Handle null value} }

Version 1.1

65

Stage 4: Close

Connect

Query Close the result set Process results

Close the statement

Close

Close the connection

Version 1.1

66

How to Close the Connection?

1. Close the ResultSet object


rset.close();

2. Close the Statement object


stmt.close();

3. Close the connection (not necessary for server-side driver)

conn.close();

Version 1.1

67

The DatabaseMetaData Object


The Connection object can be used to get a DatabaseMetaData object This object provides more than 100 methods to obtain information about the database

Version 1.1

68

How to obtain Database Metadata?

1. Get the DatabaseMetaData object


DatabaseMetaData dbmd = conn.getMetaData();

2. Use the objects methods to get the metadata


DatabaseMetaData dbmd = conn.getMetaData(); String s1 = dbmd getURL(); String s2 = dbmd.getSQLKeywords(); boolean b1 = dbmd.supportsTransactions(); boolean b2 = dbmd.supportsSelectForUpdate();

Version 1.1

69

The ResultSetMetaData Object


The ResultSet object can be used to get a ResultSetMetaData object ResultSetMetaData object provides metadata, including: Number of columns in the result set Column type Column name

Version 1.1

70

How to obtain ResultSetMetadata?

1. Get the ResultSetMetaData object


ResultSetMetaData rsmd = rset.getMetaData();

2. Use the objects methods to get the metadata


ResultSetMetaData rsmd = rset.getMetaData(); for (int i = 1; i <= rsmd.getColumnCount(); i++) { String colname = rsmd.getColumnName(i); int coltype = rsmd.getColumnType(i); }

Version 1.1

71

Mapping Database Types to Java Types


ResultSet maps database types to Java types.
ResultSet rset = stmt.executeQuery ("select ID, DATE_OF_JOIN, SUPERVISOR from STUDENT"); int id = rset.getInt(1); Date rentaldate = rset.getDate(2); String status = rset.getString(3); Col Name ID DATE_OF_JOIN SUPERVISOR
Version 1.1

Type NUMBER DATE VARCHAR2


72

Version 1.1

73

The PreparedStatement Object


A PreparedStatement object holds precompiled SQL statements Use this object for statements you want to execute more than once A prepared statement can contain variables that you supply each time you execute the statement

Version 1.1

74

How to Create a PreparedStatement?

1.

Register the driver and create the database connection

2. Create the prepared statement, identifying variables with a question mark (?)
PreparedStatement pstmt = conn.prepareStatement("update STUDENT set SUPERVISOR = ? where ID = ?"); PreparedStatement pstmt = conn.prepareStatement("select SUPERVISOR from STUDENT where ID = ?");

Version 1.1

75

How to execute PreparedStatement?


1. Supply values for the variables
pstmt.setXXX(index, value);

2. Execute the statement


pstmt.executeQuery(); pstmt.executeUpdate(); PreparedStatement pstmt = conn.prepareStatement("update STUDENT set SUPERVISOR = ? Where ID = ?"); pstmt.setString(1, "OUT"); pstmt.setInt(2, id); pstmt.executeUpdate();
Version 1.1

76

The CallableStatement Object


A CallableStatement object holds parameters for calling stored procedures A callable statement can contain variables that you supply each time you execute the call When the stored procedure returns, computed values (if any) are retrieved through the CallableStatement object

Version 1.1

77

How to Create a CallableStatement?

Register the driver and create the database connection Create the callable statement, identifying variables with a question mark (?)

CallableStatement cstmt = conn.prepareCall("{call " + ADDITEM + "(?,?,?)}"); cstmt.registerOutParameter(2,Types.INTEGER); cStmt.registerOutParameter(3,Types.DOUBLE);

Version 1.1

78

How to execute a CallableStatement?

1. Set the input parameters


cstmt.setXXX(index, value);

2. Execute the statement


cstmt.execute(statement);

3. Get the output parameters


var = cstmt.getXXX(index);

Version 1.1

79

Using Transactions
The server-side driver does not support autocommit mode With other drivers:

New connections are in autocommit mode Use conn.setAutoCommit(false) to turn autocommit off

To control transactions when you are not in autocommit mode:

conn.commit(): Commit a transaction conn.rollback(): Roll back a transaction

Version 1.1

80

Summary of JDBC Classes

DriverManager

Connection

DatabaseMetaData

Statement

ResultSet

ResultSetMetaData

Version 1.1

81

Summary
In this module you have learnt to:

Connect to a database using Java Database Connectivity (JDBC) Create and execute a query using JDBC Invoke prepared statements Commit and roll back transactions Use the Metadata objects to retrieve more information about the database or the resultset

Version 1.1

82

Version 1.1

83

Version 1.1

84

Version 1.1

85

Version 1.1

86

Version 1.1

87

Version 1.1

88

S-ar putea să vă placă și