3. Trigger Example
DELIMITER $$ -- set delimeter (allow ; inside)
CREATE TRIGGER newsCounter
AFTER INSERT ON News
FOR EACH ROW BEGIN
INSERT INTO NewsCount (newsItemCount)
(SELECT count(*) FROM News);
END;
$$
DELIMITER ; -- reset delimeter
7. Trigger Statements
DROP TRIGGER newsCounter;
SHOW TRIGGERS;
One trigger per event, per table
Can add procedural elements, such as IF
statements
See reference 4 (databasedesign-resource)
for another example
8. Stored Procedures
Why go to the trouble of extracting logic from your application, putting it into a
different format, and placing it on the database server? There are several
advantages to doing so. Here is a (incomplete) list of some of the most commonly
sited advantages:
MySQL stored procedures can greatly cut down on the amount of traffic going back
and forth over your network. (usually FASTER in general than using app program)
Stored procedures can greatly improve the security of your database server. SQL
that is executed on the server is not subject to SQL injection attacks.
Stored procedures provide a way to abstract and separate data access routines
from the business logic of your application.
Stored procedures allow these routines to be accessed by programs using different
platforms and API's, and make your applications more portable.
From source 4 (databasedesign-resource)
9. Stored Procedures
Block structured language similar to Oracle
PL/SQL and IBM DB2 SQL
Some folks recommend using MySQL query
browser to aid creation, but can be done from
command line
Seeing what you have
• SHOW PROCEDURE STATUS;
• SHOW PROCEUDRE LIKE ‘%Test%’;
• SHOW CREATE PROCEDURE myproc;
10. Stored Procedures
Sample DB
-- create News table, be sure to be in a 'test' DB
CREATE TABLE News
(NewsID int auto_increment not null,
Title varchar(32),
primary key(NewsID))
12. Stored Procedures
Using cursors
• Let’s us loop on each row returned from a query
(the result set)
• see design-resources link (also on next slide)
14. Program DB Access
First:
• Chapter 9 Slides 18-37 from Elmasri 5th edition
Some sources for Java access
• http://www.kitebird.com/articles/jdbc.html
• http://www.cs.ucdavis.edu/~devanbu/teaching/160/docs/mys
ql_java.pdf
• http://www.romow.com/computer-blog/how-to-use-mysql-with-java
/
Can also access mysql with Perl, PHP, Python, Ruby
Editor's Notes
causes all news items to be deleted when the corresponding news category is deleted
<number>
updates count of news items when new item is added, of course we need one for deleting news items too
<number>