Advanced Java Programming – Eran Toch Methodologies in Information System Development Tutorial: Advanced Java Programming and Database connection Eran.

Slides:



Advertisements
Similar presentations
Yoshi
Advertisements

„Exceptions”. Exceptions Handling errors with exceptions Golden rule of programming: Errors occur in software programs. What really matters is what happens.
Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.
Java Exception Very slightly modified from K.P. Chow University of Hong Kong (some slides from S.M. Yiu)
Exceptions Any number of exceptional circumstances may arise during program execution that cause trouble import java.io.*; class IOExample { public static.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
15-Jun-15 JDBC. JDBC is a Sun trademark It is often taken to stand for Java Database Connectivity Java is very standardized, but there are many versions.
JDBC Overview Autumn 2001 Lecturer: C. DeJong. Relational Databases widespread use used via SQL (Structured Query Language) freely available powerful.
Handling Errors with Exception (in Java) Project 10 CSC 420.
Java Exception Handling ● Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions: – Examples:
Murali Mani Web Interface. Murali Mani Options PHP with mySQL JSP/Servlets with JDBC on mySQL/Oracle Others …
Java Exceptions. Intro to Exceptions  What are exceptions? –Events that occur during the execution of a program that interrupt the normal flow of control.
Java MS Access database connectivity Follow these steps: 1)Go to the start->Control Panel->Administrative Tools- > data sources. 2)Click Add button and.
CS203 Java Object Oriented Programming Errors and Exception Handling.
Helena Pomezná, ciz034 St. skupina: L392 FEI, VŠB-TUO Ak. rok. 2002/2003 Download:
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
Java Programming Exception Handling. The exception handling is one of the powerful mechanism provided in java. It provides the mechanism to handle the.
CSCI 6962: Server-side Design and Programming JDBC Database Programming.
CS178 Database Management “JDBC”. What is JDBC ? JDBC stands for “Java DataBase Connectivity” The standard interface for communication between a Java.
JDBC. What is JDBC JDBC is an acronym for –Java Data Base Connectivity. It allows java/jsp program to connect to any database.
Beginning Databases with JDBC Mike Bradley Adapted from and notes by Kevin Parker, Ph.D.
Introduction to Java Development with IDS Jean Georges Perrin IIUG I04 Tuesday, October 3 rd :00 – 10:00. Platform: IDS, Java.
Georgia Institute of Technology Making Text for the Web part 5 Barb Ericson Georgia Institute of Technology March 2006.
MySQL, Java, and JDBC CSE 3330 Southern Methodist University.
JDBC Tutorial MIE456 - Information Systems Infrastructure II Vinod Muthusamy November 4, 2004.
JAVA Database Access. JDBC The Java Database Connectivity (JDBC) API is the industry standard for database- independent connectivity between the Java.
CS 2511 Fall  Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:  Examples: Out.
Handling Exceptions in java. Exception handling blocks try { body-code } catch (exception-classname variable-name) { handler-code }
Servlets Database Access. Agenda:  Setup Java Environment  Install Database  Install Database Drivers  Create Table and add records  Accessing a.
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.
Index and JDBC/JSP tutorial Professor: Dr. Shu-Ching Chen TA: Hsin-Yu Ha.
Chapter 25 Databases. Chapter Scope Database concepts Tables and queries SQL statements Managing data in a database Java Foundations, 3rd Edition, Lewis/DePasquale/Chase25.
Introduction to Programming G50PRO University of Nottingham Unit 11 : Files Input/Ouput Paul Tennent
JDBC Database Programming in Java Prepared by., Mrs.S.Amudha AP/SWE.
JDBC. Java.sql.package The java.sql package contains various interfaces and classes used by the JDBC API. This collection of interfaces and classes enable.
Java and Databases. JDBC Architecture Java Application JDBC API Data Base Drivers AccessSQL Server DB2InformixMySQLSybase.
COMP 321 Week 4. Overview Normalization Entity-Relationship Diagrams SQL JDBC/JDBC Drivers hsqldb Lab 4-1 Introduction.
EXAMPLE I An application showing JDBC access to Cloudscape.
Tasks Needed for MissionMapEditor Martin Q. Zhao September 18, 2010.
CSI 3125, Preliminaries, page 1 JDBC. CSI 3125, Preliminaries, page 2 JDBC JDBC stands for Java Database Connectivity, which is a standard Java API (application.
Basics of JDBC.
Copyright © Curt Hill Error Handling in Java Throwing and catching exceptions.
Web Programming Assistant Professor Xiaozhong Liu
JDBC Java and Databases. SWC – JDBC JDBC – Java DataBase Connectivity An API (i.e. a set of classes and methods), for working with databases in.
1 Download current version of Tomcat from: g/tomcat/ g/tomcat/ Install it in: C:\Program Files\Apache.
SQL pepper. Why SQL File I/O is a great deal of code Optimal file organization and indexing is critical and a great deal of code and theory implementation.
Garbage Collection It Is A Way To Destroy The Unused Objects. To do so, we were using free() function in C language and delete() in C++. But, in java it.
JDBC. What is JDBC JDBC is an acronym for –Java Data Base Connectivity. It allows java program to connect to any database.
Agenda Introduction Errors and Exception Exception Hierarchy Classification of Exceptions Built in Exceptions Exception Handling in Java User defined.
1. Writing a Java program to connect to SQL Server 2008 and Create a table Populate the table (insert data) Perform queries to retrieve information from.
CS320 Web and Internet Programming Database Access with JDBC Chengyu Sun California State University, Los Angeles.
Database Programming Basic JDBC Programming Concepts.
Lec - 14.
JDBC 15-Apr-18.
Java Exceptions a quick review….
Exceptions In this lecture:
Introduction to Exceptions in Java
Advanced Web Automation Using Selenium
JDBC 21-Aug-18.
HW#4 Making Simple BBS Using JDBC
JDBC 15-Nov-18.
Java Exception Very slightly modified from K.P. Chow
Java Exception Very slightly modified from K.P. Chow
Bolat Azamat, Kim Dongmin
Intro to Exceptions (c) Eraj Basnayake
Java Exceptions Dan Fleck CS211.
JDBC Example.
Java Basics Exception Handling.
JDBC – Java DataBase Connectivity
Presentation transcript:

Advanced Java Programming – Eran Toch Methodologies in Information System Development Tutorial: Advanced Java Programming and Database connection Eran Toch Methodologies in the Development of Information Systems November 2003

2 Advanced Java Programming – Eran Toch Methodologies in Information System Development Agenda Exceptions and Error Handling –What is it and why do we need it? –The try, catch, finally procedure Database Access with JDBC –Installations –Connecting and querying the database –Complete example References

3 Advanced Java Programming – Eran Toch Methodologies in Information System Development Exceptions - Introduction Definition: An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. What’s wrong with using the return value for error handling? –Advantage 1: Separating Error Handling Code from "Regular" Code –Advantage 2: Propagating Errors Up the Call Stack –Advantage 3: Grouping Error Types and Error Differentiation

4 Advanced Java Programming – Eran Toch Methodologies in Information System Development Exceptions – Advantage 1 Separating Error Handling Code from "Regular" Code: errorCodeType readFile { initialize errorCode = 0; open the file; if (theFileIsOpen) { determine the length of the file; if (gotTheFileLength) { allocate that much memory; if (gotEnoughMemory) { read the file into memory; if (readFailed) { errorCode = -1; } } else { errorCode = -2; }... readFile { try { open the file; determine its size; allocate that much memory; read the file into memory; close the file; } catch (fileOpenFailed) { doSomething; } catch (sizeDeterminationFailed) { doSomething; } catch (memoryAllocationFailed) { doSomething; } catch (readFailed) { doSomething; } catch (fileCloseFailed) { doSomething; } Without ExceptionWith Exception

5 Advanced Java Programming – Eran Toch Methodologies in Information System Development The try Block try block: A try statement must be accompanied by at least one catch block or one finally block. try { System.out.println("Entering try statement"); out = new PrintWriter(new FileWriter("OutFile.txt")); } for (int i = 0; i < size; i++) out.println("Value at: " + i + " = " + victor.elementAt(i));

6 Advanced Java Programming – Eran Toch Methodologies in Information System Development The catch Block catch block handles the exception: Multiple catch blocks can be placed, each handling a different type of exception try {... } catch (ArrayIndexOutOfBoundsException e) { System.err.println("Caught ArrayIndexOutOfBoundsException: " + e.getMessage()); } catch (IOException e) { System.err.println("Caught IOException: " + e.getMessage()); }

7 Advanced Java Programming – Eran Toch Methodologies in Information System Development Catching Multiple Exceptions Java exceptions are Throwable objects Catching MyException will catch both the subclasses. Catching Exception will catch all types of Exceptions Throwable Exception MyException MySpecificException1MySpecificException2

8 Advanced Java Programming – Eran Toch Methodologies in Information System Development Catching Multiple Exceptions – cont’d Example: The following catch block, will catch all types of exceptions: } catch (Exception e) { System.err.println("Exception caught: " + e.getMessage()); }

9 Advanced Java Programming – Eran Toch Methodologies in Information System Development The finally Block We can never be sure that either the try block or the finally block will be fully executed. finally block code will always be executed: Used frequently for cleanup processes. finally { if (out != null) { System.out.println("Closing PrintWriter"); out.close(); } else { System.out.println("PrintWriter not open"); }

10 Advanced Java Programming – Eran Toch Methodologies in Information System Development Putting it All Together public void writeList() { PrintWriter out = null; try { System.out.println("Entering try statement"); out = new PrintWriter( new FileWriter("OutFile.txt")); for (int i = 0; i < size; i++) out.println("Value at: " + i + " = " + victor.elementAt(i)); } catch (ArrayIndexOutOfBoundsException e) { System.err.println("Caught ArrayIndexOutOfBoundsException: " + e.getMessage()); } catch (IOException e) { System.err.println("Caught IOException: " + e.getMessage()); } finally { if (out != null) { System.out.println("Closing PrintWriter"); out.close(); } else { System.out.println("PrintWriter not open"); }

11 Advanced Java Programming – Eran Toch Methodologies in Information System Development throw Statement All Java methods use the throw statement to throw an exception The method must declare that it might throw something, by using the throws statement public Object pop() throws EmptyStackException { Object obj; if (size == 0) throw new EmptyStackException(“exception text”); obj = objectAt(size - 1); setObjectAt(size - 1, null); size--; return obj; }

12 Advanced Java Programming – Eran Toch Methodologies in Information System Development Exceptions and JavaDoc Exception can be documented by Javadoc using statement /** * regular javadoc text… the Driver was not found. the the DriverManager.getConnection * method returned an error. */ public void createConnection()throws SQLException, Exception{

13 Advanced Java Programming – Eran Toch Methodologies in Information System Development Agenda Exceptions and Error Handling –What is it and why do we need it? –The try, catch, finally procedure Database Access with JDBC –Installations –Connecting and querying the database –Complete example References

14 Advanced Java Programming – Eran Toch Methodologies in Information System Development Database Connection - Overview Four stages: –Install and configure the database –Download and configure the JDBC –Create a connection to the database –Access the database In this tutorial, examples will be based on MySQL. The reference section include a link to instructions for MS Access.reference

15 Advanced Java Programming – Eran Toch Methodologies in Information System Development Database Install Download the MySQL database from: Install it Create a specific database: create database mytest; Create a user account: grant all on mytest.* to eran identified by ‘1234’

16 Advanced Java Programming – Eran Toch Methodologies in Information System Development JDBC Install Download Connector/J from: Unzip it In order the library to be found, either: –Copy the.jar file to: $JAVA_HOME/jre/lib/ext –Or, add a classpath to the JDBC: C:\> set CLASSPATH=\path\to\mysql-connector-java-[version]- bin.jar;%CLASSPATH%

17 Advanced Java Programming – Eran Toch Methodologies in Information System Development Accessing Database 1.Load the driver 2.Creating a connection object 3.Create a statement object 4.Execute an SQL query and get results using the ResultSet object

18 Advanced Java Programming – Eran Toch Methodologies in Information System Development Example – Database Management mysql> create database mytest; Query OK, 1 row affected (0.05 sec) mysql> grant all on *.* to identified by '1234'; Query OK, 0 rows affected (0.14 sec) mysql>create table phones (name varchar(255) not null unique key, phone varchar(25) not null); mysql>describe phones; | Field | Type | Null | Key | Default | Extra | | name | varchar(255) | | PRI | | | | phone | varchar(25) | | | | | mysql> insert into phones values ('Eran Toch', ' '); Query OK, 1 row affected (0.11 sec) Creating the DB Creating user account Creating the ‘phones’ table Is everything alright? Let’s see… Inserting some data

19 Advanced Java Programming – Eran Toch Methodologies in Information System Development Example – Connection import java.sql.*; public class SQLConnect { Connection conn = null; Statement stmt = null; ResultSet rs = null; public SQLConnect(){} public void createConnection(){ try{ Class.forName("com.mysql.jdbc.Driver").newInstance(); } catch (Exception E){ System.out.println(E); } try{ conn = DriverManager.getConnection("jdbc:mysql://localhost/mytest?user=test master&password=1234"); } catch (SQLException E){ System.out.println(E); } Importing java.sql.* that contains all the classes we need Connection, Statement and ResultSet are defined as class variables Dynamically loading the specific JDBC driver. The runtime environment must know where the library is located! Connecting to the database using the url

20 Advanced Java Programming – Eran Toch Methodologies in Information System Development Example – Locating Libraries If the following error message occurs: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver java.sql.SQLException: No suitable driver Then the driver was not found. –For Eclipse, add it in the project properties window –For runtime, add it to the classpath Project properties window in Eclipse

21 Advanced Java Programming – Eran Toch Methodologies in Information System Development Example – Access and Query public String getPhones(){ String output = ""; try { stmt = conn.createStatement(); rs = stmt.executeQuery("SELECT * FROM phones"); if (rs != null){ while (rs.next()){ output += rs.getString("phone") + "\n"; } catch (Exception E){ System.out.println(E.getMessage()); } Creating a statement Creating a ResultSet, based on a SQL statement Going through the ResultSet by using rs.next(). Remember – you need to call the next method before you start reading from the ResultSet Reading a field from the ResultSet

22 Advanced Java Programming – Eran Toch Methodologies in Information System Development Example – Cleaning off finally { if (rs != null) { try { rs.close(); } catch (SQLException sqlEx) {} rs = null; } if (stmt != null) { try { stmt.close(); } catch (SQLException sqlEx) {} stmt = null; } return output; } public void closeConnection(){ if (conn != null){ try { conn.close(); } catch (SQLException sqlEx){} conn = null; } Cleaning off is best done in the “finally” clause Cleaning off ResultSet Cleaning off Statement, after the ResultSet Cleaning off the connection, in a different method (why?)

23 Advanced Java Programming – Eran Toch Methodologies in Information System Development Example – Test Client public class Test { public static void main(String[] args) { SQLConnect connect = new SQLConnect(); connect.createConnection(); String allPhones = connect.getPhones(); connect.closeConnection(); System.out.println("phones:"); System.out.println(allPhones); } Output phones:

24 Advanced Java Programming – Eran Toch Methodologies in Information System Development Agenda Exceptions and Error Handling –What is it and why do we need it? –The try, catch, finally procedure Database Access with JDBC –Installations –Connecting and querying the database –Complete example References

25 Advanced Java Programming – Eran Toch Methodologies in Information System Development References Exception handling in the Java tutorial: JDBC Tutorial: MySQL Tutorial: MySQL JDBC Connector/J Tutorial: Using Microsoft Access with JDBC: access.html access.html