Error Handling Summary of the next few pages: Error Handling Cursors.

Slides:



Advertisements
Similar presentations
JQuery MessageBoard. Lets use jQuery and AJAX in combination with a database to update and retrieve information without refreshing the page. Here we will.
Advertisements

AN INTRODUCTION TO PL/SQL Mehdi Azarmi 1. Introduction PL/SQL is Oracle's procedural language extension to SQL, the non-procedural relational database.
Loops (Part 1) Computer Science Erwin High School Fall 2014.
Chapter 4B: More Advanced PL/SQL Programming
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Bordoloi and Bock CURSORS. Bordoloi and Bock CURSOR MANIPULATION To process an SQL statement, ORACLE needs to create an area of memory known as the context.
PL / SQL P rocedural L anguage / S tructured Q uery L anguage Chapter 7 in Lab Reference.
MySQL in PHP – Page 1 of 17CSCI 2910 – Client/Server-Side Programming CSCI 2910 Client/Server-Side Programming Topic: MySQL in PHP Reading: Williams &
Cursor and Exception Handling By Nidhi Bhatnagar.
Oracle10g Developer: PL/SQL Programming1 Objectives Manipulating data with cursors Managing errors with exception handlers Addressing exception-handling.
Chapter 4 Cursors and Exception Handling Oracle10g Developer:
PHP meets MySQL.
Stored Procedures, Transactions, and Error-Handling
08/10/ Iteration Loops For … To … Next. 208/10/2015 Learning Objectives Define a program loop. State when a loop will end. State when the For.
Python Programming Chapter 6: Iteration Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
Stored procedures1 Stored procedures and functions Procedures and functions stored in the database.
Copyright © Curt Hill Stored Procedures In Transact-SQL.
JDBC Java and Databases. RHS – SOC 2 JDBC JDBC – Java DataBase Connectivity An API (i.e. a set of classes and methods), for working with databases in.
Advanced SQL: Cursors & Stored Procedures
CpSc 462/662: Database Management Systems (DBMS) (TEXNH Approach) Stored Procedure James Wang.
Stored Procedures Week 9. Test Details Stored Procedures SQL can call code written in iSeries High Level Languages –Called stored procedures SQL has.
1 Real SQL Programming Persistent Stored Modules (PSM) PL/SQL Embedded SQL.
Trapping Oracle Server Exceptions. 2 home back first prev next last What Will I Learn? Describe and provide an example of an error defined by the Oracle.
Chapter 15 Introduction to PL/SQL. Chapter Objectives  Explain the benefits of using PL/SQL blocks versus several SQL statements  Identify the sections.
PL/SQLPL/SQL Oracle11g: PL/SQL Programming Chapter 4 Cursors and Exception Handling.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
Introduction to Explicit Cursors. 2 home back first prev next last What Will I Learn? Distinguish between an implicit and an explicit cursor Describe.
Professor: Dr. Shu-Ching Chen TA: Hsin-Yu Ha Function, Trigger used in PosgreSQL.
1 Intro stored procedures Declaring parameters Using in a sproc Intro to transactions Concurrency control & recovery States of transactions Desirable.
Copyright © 2013 Curt Hill Triggers The Generation of Indirect Actions.
Instructor: Craig Duckett Lecture 07: Tuesday, October 20 th, 2015 Conflicts and Isolation, MySQL Workbench 1 BIT275: Database Design (Fall 2015)
1 Stored Procedures in MySQL Part I. 2 Objectives SQL Vs. MySQL SP MySQL SP Parameters MySQL SP Control Structures.
Chapter 8 Advanced SQL Pearson Education © Chapter 8 - Objectives How to use the SQL programming language How to use SQL cursors How to create stored.
Advanced SQL: Cursors & Stored Procedures Instructor: Mohamed Eltabakh 1.
Arrays and Loops. Learning Objectives By the end of this lecture, you should be able to: – Understand what a loop is – Appreciate the need for loops and.
1 Section 10 - Embedded SQL u Many computer languages allow you to embed SQL statements within the code (e.g. COBOL, PowerBuilder, C++, PL/SQL, etc.) u.
CS422 Principles of Database Systems Stored Procedures and Triggers Chengyu Sun California State University, Los Angeles.
1. Advanced SQL Functions Procedural Constructs Triggers.
ASP.NET Programming with C# and SQL Server First Edition
Discussion 4 eecs 183 Hannah Westra.
Lesson #5 Repetition and Loops.
Generics, Exceptions and Undo Command
Manipulating Pictures, Arrays, and Loops part 2
Lesson #5 Repetition and Loops.
Foundations of Programming: Arrays
Oracle11g: PL/SQL Programming Chapter 4 Cursors and Exception Handling.
Database Construction (and Usage)
Incrementing ITP © Ron Poet Lecture 8.
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
MySQL - Creating donorof database offline
ISC440: Web Programming 2 Server-side Scripting PHP 3
Arrays & Functions Lesson xx
Arrays, For loop While loop Do while loop
Iteration with While You can say that again.
File Handling Programming Guides.
Conditions and Ifs BIS1523 – Lecture 8.
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
Lesson #5 Repetition and Loops.
Building Web Applications
File I/O in C Lecture 7 Narrator: Lecture 7: File I/O in C.
Functions Pass By Value Pass by Reference
Module 4 Loops.
Instructor: Craig Duckett
Unit I-2.
Problem Solving Designing Algorithms.
Please use speaker notes for additional information!
Lesson #5 Repetition and Loops.
Manipulating Pictures, Arrays, and Loops
SQL – Constraints & Triggers
ICS103: Programming in C 5: Repetition and Loop Statements
Presentation transcript:

Error Handling Summary of the next few pages: Error Handling Cursors

Sample Problem: Log Of Failures mysql> CREATE TABLE t2 s1 INT, PRIMARY KEY (s1)) engine=innodb;// mysql> CREATE TABLE t3 (s1 INT, KEY (s1), FOREIGN KEY (s1) REFERENCES t2 (s1)) mysql> INSERT INTO t3 VALUES (5);// ... ERROR 1216 (23000): Cannot add or update a child row: a foreign key constraint fails I start off by making a primarykey table, and a foreignkey table. I'm using InnoDB, so foreign key checks should work. Then I try to insert a value in the foreignkey table that isn't in the primarykey table. That will fail, I know. This is just a quick way to find out what the error number is for the condition. It's Error Number one two one six.

Sample Problem: Log Of Failures Next, I make a table in which I am going to store errors that occur when I'm trying to do my inserts. CREATE TABLE error_log (error_message CHAR(80))// Next I’m create a procedure that will insert then error in the error_log table. CREATE PROCEDURE p22 (parameter1 INT) BEGIN DECLARE EXIT HANDLER FOR 1216 INSERT INTO error_log VALUES (CONCAT('Time: ',current_date, '. Foreign Key Reference Failure For Value = ',parameter1)); INSERT INTO t3 VALUES (parameter1); END;//

Sample Problem: Log Of Failures continued Here's my procedure. The first statement here, DECLARE EXIT HANDLER, is what handles exceptions. This is saying that if error one two one six happens, then the procedure will insert a row into the error log table. The word EXIT means "we'll exit from the compound statement when we're done". CALL p22 (5) // Now let's call the procedure. It will fail, of course, because the value five doesn't appear in the primary key table. But there is no error return, because the error is handled inside the procedure. When I look at the contents of table t3, I see that nothing got inserted into table t3. But when I look at the contents of table error_log, I see that something did get added into table error_log. This tells me that an INSERT into table t3 failed.

Error Handling (continued) DECLARE HANDLER syntax DECLARE { EXIT | CONTINUE } HANDLER FOR { error-number | { SQLSTATE error-string } | condition } SQL statement Okay, so that's how a handler works. It's a piece of code that gets triggered when an error happens. MySQL in fact allows two kinds of handlers. One is the EXIT handler, which we just saw. Next we'll look at the other kind of handler, the CONTINUE handler. It's similar to the EXIT handler, but after it executes, the play continues. There's no exit from the compound statement.

Error Handling (continued) DECLARE CONTINUE HANDLER example CREATE TABLE t4 (s1 int, primary key(s1));// CREATE PROCEDURE p23 () BEGIN DECLARE CONTINUE HANDLER FOR SQLSTATE '23000' SET @x2 = 1; SET @x = 1; INSERT INTO t4 VALUES (1); SET @x = 2; SET @x = 3; END;//

DECLARE CONTINUE HANDLER example I'll define the handler for an SQLSTATE value this time. Remember that I used a MySQL error code last time, error one two one six. Actually, SQLSTATE two three zero zero zero is a little more general. It happens for either a foreignkey violation or a Primarykey violation. The first statement of this procedure that gets executed is "SET @x = 1". Then the value one gets inserted into the primarykey table. Then the value of @x becomes two. Then an attempt is made to insert the same value into the primarykey table again. But it fails, because primary keys must be unique. Now, because the insert fails, the handler takes over. The next statement that gets executed is the handler's statement, so @x2 gets set to one. But that's not the end. This is a CONTINUE handler. So now the procedure goes back to where we were, after the failed insert statement. And it sets @x to three. mysql> CALL p23()// mysql> SELECT @x, @x2//

CURSORS A cursor is used to iterate through a set of rows returned by a query so that we can process each individual row. Summary of things that we can do with cursors: DECLARE cursor-name CURSOR FOR SELECT ...; OPEN cursor-name; FETCH cursor-name INTO variable [, variable]; CLOSE cursor-name; Now let's look at cursors. We have a somewhat incomplete implementation of the syntax for cursors inside stored procedures. But we can do the main things. We can declare a cursor, we can open it, we can fetch from it, and we can close it.

CURSORS Cursor Example CREATE PROCEDURE p25 (OUT return_val INT) BEGIN DECLARE a,b INT; DECLARE cur_1 CURSOR FOR SELECT s1 FROM t; DECLARE CONTINUE HANDLER FOR NOT FOUND SET b = 1; OPEN cur_1; REPEAT FETCH cur_1 INTO a; UNTIL b = 1 END REPEAT; CLOSE cur_1; SET return_val = a; END;//

CURSORS continued The procedure starts with three DECLARE statements. Incidentally, the order is important. First declare variables. Then declare conditions. Then declare cursors. Then, declare handlers. If you put them in the wrong order, you will get an error message. We next have a declaration of a cursor. This looks almost exactly like what's in embedded SQL, for anyone who has worked with that. The final declaration, as I said, is of a handler. This continue handler does not refer to a MySQL error number or to an SQLSTATE value. Instead it uses NOT FOUND. This happens to be the same as error one three one six or SQLSTATE '02000'. The first executable statement is OPEN cur_1. Since cur_1 is associated with "SELECT s1 FROM t", the procedure will SELECT s1 FROM t, producing a result set. The first FETCH statement here will cause a single row to be retrieved from the result set that the SELECT produced. Since we know that there are several rows in table t, we know that this statement will happen several times that is, it is in a loop. Eventually, MySQL will have no more rows to fetch. At that point, we will reach the statement that's in the CONTINUE handler. That is, set variable b to one.

CURSORS continued 7. Therefore the condition UNTIL b = 1 is now true. Therefore the loop ends. So now I close the cursor. If I didn't, it would be closed automatically when the compound statement ends. But I think depending on automatic behaviour looks a tad sloppy. 8. Now we'll assign our local variable to an output parameter, so that the results will be visible after the procedure finishes. Now lets call the procedure mysql> CALL p25(@return_val)// Query OK, 0 rows affected (0.00 sec) mysql> SELECT @return_val// Here you see that the return_val parameter got a value of 5, which is right, because that is what is in the last row of table t. So we know that the cursor worked, and we know that the handler worked.