Postgres For Java Programmers
Postgres For Java Programmers
DB2
Connect
to newly
installed
server
Connection dbConnect;!
Statement sql; // Our statement to run queries with!
DatabaseMetaData dbmd; // This is basically info the driver delivers!
// about the DB it just connected to. I use!
// it to get the DB version to confirm the!
// connection in this example.!
}!
[ <<label>> ]
[ DECLARE
declarations ]
BEGIN
statements
END [ label ];
SELECT INTO!
• SELECT INTO target select_expressions FROM ...;!
• SELECT INTO myrec * FROM emp WHERE empname = myname;!
35
PL/pgSQL Control Structures !
RETURN!
• RETURN expression;!
• This form is to be used for PL/pgSQL functions that do not return a set.!
IF-THEN-ELSE
IF boolean-expression THEN
statements
ELSE
statements
END IF;
LOOP
-- some computations
EXIT WHEN count > 0; -- same result as
previous example
END LOOP;
BEGIN
-- some computations
IF stocks > 100000 THEN
EXIT; -- causes exit from the BEGIN
block
END IF;
END;
WHILE
WHILE amount_owed > 0 AND gift_certificate_balance >
0 LOOP
-- some computations here
END LOOP;
FOR
FOR i IN 1..10 LOOP
-- some computations here
RAISE NOTICE 'i is %', i;
END LOOP;
40
Copyright 2010 EnterpriseDB Corporation. All rights Reserved 40
Loop through Query Results
[ <<label>> ]
FOR record_or_row IN query LOOP
statements
END LOOP [ label ];
41
Copyright 2010 EnterpriseDB Corporation. All rights Reserved 41
FOR-IN-EXECUTE
[ <<label>> ]
FOR record_or_row IN EXECUTE text_expression LOOP
statements
END LOOP [ label ];
• This is like the previous form, except that the source SELECT statement is specified
as a string expression, which is evaluated and replanned on each entry to the FOR
loop.
• This allows the programmer to choose the speed of a preplanned query or the
flexibility of a dynamic query, just as with a plain EXECUTE statement
42
Copyright 2010 EnterpriseDB Corporation. All rights Reserved 42
Checking For Errors
By default, any error occurring in a PL/pgSQL function aborts execution
of the function
You can trap errors and recover from them by using a BEGIN block
with an EXCEPTION clause
43
Copyright 2010 EnterpriseDB Corporation. All rights Reserved 43
Checking For Errors (cont)
CREATE TABLE db (a INT PRIMARY KEY, b TEXT);
CREATE FUNCTION merge_db(key INT, data TEXT) RETURNS VOID AS
$$
BEGIN
LOOP
UPDATE db SET b = data WHERE a = key;
IF found THEN
RETURN;
END IF;
BEGIN
INSERT INTO db(a,b) VALUES (key, data);
RETURN;
EXCEPTION WHEN unique_violation THEN
-- do nothing
END;
END LOOP;
END;
$$ LANGUAGE plpgsql;
44
Copyright 2010 EnterpriseDB Corporation. All rights Reserved 44
PL/pgSQL Cursors
Declaring Cursors
• DECLARE curs1 refcursor;!
• DECLARE curs2 CURSOR FOR SELECT * FROM tenk1;!
• DECLARE curs3 CURSOR (key integer) IS SELECT * FROM
tenk1 WHERE unique1 = key;!
Opening Cursors
• OPEN FOR query!
• OPEN unbound_cursor FOR query;!
– OPEN curs1 FOR SELECT * FROM foo WHERE key = mykey;!
• OPEN FOR EXECUTE!
• OPEN unbound_cursor FOR EXECUTE query_string;!
– OPEN curs1 FOR EXECUTE 'SELECT * FROM ' || quote_ident
($1);!
45
Copyright 2010 EnterpriseDB Corporation. All rights Reserved 45
PL/pgSQL Cursors (cont)
Opening a Bound Cursor
• OPEN bound_cursor [ ( argument_values ) ];
DECLARE
curs2 CURSOR FOR SELECT * FROM tenk1;
curs3 CURSOR (key integer) IS SELECT * FROM tenk1 WHERE
unique1 = key;
OPEN curs2;
OPEN curs3(42);
46
Copyright 2010 EnterpriseDB Corporation. All rights Reserved 46
PL/pgSQL Cursors (cont)
FETCH
• FETCH cursor INTO target;
• FETCH retrieves the next row from the cursor into a target, which may
be a row variable, a record variable, or a comma-separated list of
simple variables, just like SELECT INTO.
• As with SELECT INTO, the special variable FOUND may be checked
to see whether a row was obtained or not.
– FETCH curs1 INTO rowvar;!
– FETCH curs2 INTO foo, bar, baz;!
CLOSE
• CLOSE closes the portal underlying an open cursor.
• This can be used to release resources earlier than end of transaction, or
to free up the cursor variable to be opened again.
– CLOSE curs1;!
47
Copyright 2010 EnterpriseDB Corporation. All rights Reserved 47
Triggers
Created with the CREATE FUNCTION command
Several special variables are created automatically in the top-level
block.
• NEW
– Data type RECORD; variable holding the new database row
for INSERT/UPDATE operations in row-level triggers. This
variable is NULL in statement-level triggers.
• OLD
– Data type RECORD; variable holding the old database row
for UPDATE/DELETE operations in row-level triggers. This
variable is NULL in statement-level triggers.
• TG_NAME
– Data type name; variable that contains the name of the trigger
actually fired.
48
Copyright 2010 EnterpriseDB Corporation. All rights Reserved 48
Triggers (Contd.)
• TG_WHEN
– Data type text; a string of either BEFORE or AFTER
depending on the trigger's definition.
• TG_LEVEL
– Data type text; a string of either ROW or STATEMENT
depending on the trigger's definition.
• TG_OP
– Data type text; a string of INSERT, UPDATE, or DELETE
telling for which operation the trigger was fired.
• TG_RELNAME
– Data type name; the name of the table that caused the trigger
invocation.
• TG_NARGS
– Data type integer; the number of arguments given to the
trigger procedure in the CREATE TRIGGER statement.
49
Copyright 2010 EnterpriseDB Corporation. All rights Reserved 49
Triggers (cont)
• Note: A trigger function must return either NULL or a record/row value having
exactly the structure of the table the trigger was fired for.
• The return value of a BEFORE or AFTER statement-level trigger or an AFTER
row-level trigger is always ignored; it may as well be null. However, any of these
types of triggers can still abort the entire operation by raising an error.
50
Copyright 2010 EnterpriseDB Corporation. All rights Reserved 50
Summary
51
Copyright 2010 EnterpriseDB Corporation. All rights Reserved 51
Lab Exercises 1
• Evaluate each of the following declarations. Determine which of them
are not legal and explain why.
– DECLARE v_name,v_dept VARCHAR(14);
– DECLARE v_test NUMERIC(5);
– DECLARE V_MAXSALARY NUMERIC(7,2) = 5000;
– DECLARE V_JOINDATE BOOLEAN := NOW();
• In each of the following assignments, determine the data type of the
resulting expression.
– v_email := v_firstname || to_char(v_empno);
– v_confirm := to_date('20-JAN-1999', 'DD-MON-YYYY');
– v_sal := (1000*12) + 500
– v_test := FALSE;
– v_temp := v_temp1 < (v_temp2/ 3);
– v_var := now();
52
Copyright 2010 EnterpriseDB Corporation. All rights Reserved 52
Lab Exercise 2
DECLARE
v_custid numeric(4) := 1600;
v_custname VARCHAR(300) := 'Women Sports Club';
v_new_custid numeric(3) := 500;
BEGIN
DECLARE
v_custid numeric(4) := 0;
v_custname VARCHAR(300) := 'Shape up Sports Club';
v_new_custid numeric(3) := 300;
v_new_custname VARCHAR(300) := 'Jansports Club';
BEGIN
v_custid := v_new_custid;
v_custname := v_custname || ' ' || v_new_custname;
END;
v_custid := (v_custid *12) / 10;
END;
Evaluate the PL/SQL block given above and determine the data type and value of each of the following
variables according to the rules of scoping:
a. The value of V_CUSTID at position 1 is:
b. The value of V_CUSTNAME at position 1 is:
c. The value of V_NEW_CUSTID at position 2 is:
d. The value of V_NEW_CUSTNAME at position 1 is:
e. The value of V_CUSTID at position 2 is:
f. The value of V_CUSTNAME at position 2 is:
g. v_custid at position 3 and v_custname at position 3.
53
Copyright 2010 EnterpriseDB Corporation. All rights Reserved 53
Lab Exercise 3
Create a PL/pgSQL function which can take integer and returns
integer.
Create a PL/pgSQL block to retrieve the name and department ID of
each employee from the EMP table for those employees whose
EMPNO is less than 7898.
From the values retrieved from the emp table, populate two tables
using PL/pgSQL, one to store the records of the employee names and
the other to store the records of their department IDs.
Using a loop, retrieve the employee name information and the salary
information from the PL/pgSQL and display it in the window. Display
these details for the first 15 employees in the PL/SQL tables.
Eg.
Employee Name: Steve Department_id: 90
Employee Name: Mac Department_id: 80
54
Copyright 2010 EnterpriseDB Corporation. All rights Reserved 54
Lab Exercise 4
55
Copyright 2010 EnterpriseDB Corporation. All rights Reserved 55