PESIT Bangalore South Campus Hosur road, 1km before Electronic City, Bengaluru -100 Department of Information Science and Engineering

Similar documents
PESIT Bangalore South Campus

Hosur road, 1km before Electronic City, Bengaluru Date : 4/10/17 Max Marks : 50. Subject & Code : JAVA and J2EE (10CS753) Section : A,B,C

Synchronization synchronization.

04-Java Multithreading

Unit 4. Thread class & Runnable Interface. Inter Thread Communication

UNIT-3 : MULTI THREADED PROGRAMMING, EVENT HANDLING. A Multithreaded program contains two or more parts that can run concurrently.

MYcsvtu Notes. Java Programming Lab Manual

Multithreaded Programming

Unit - IV Multi-Threading

JAVA. Lab 12 & 13: Multithreading

You write standard JDBC API application and plug in the appropriate JDBC driver for the database the you want to use. Java applet, app or servlets

try { Class.forName( "sun.jdbc.odbc.jdbcodbcdriver"); Database = DriverManager.getConnection(url,userID,password);

JDBC Architecture. JDBC API: This provides the application-to- JDBC Manager connection.

PERSİSTENCE OBJECT RELATİON MAPPİNG

FORTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLIGY- MARCH, 2012 OOP THROUGH JAVA (Common to CT, CM and IF)

Method Of Key Event Key Listener must implement three methods, keypressed(), keyreleased() & keytyped(). 1) keypressed() : will run whenever a key is

CSIS 10A Practice Final Exam Solutions

SQL and Java. Database Systems Lecture 20 Natasha Alechina

Top 50 JDBC Interview Questions and Answers

JDBC, Transactions. Niklas Fors JDBC 1 / 38

Lab # 9. Java to Database Connection

Cyrus Shahabi Computer Science Department University of Southern California C. Shahabi

Application Programming for Relational Databases

Database Programming Overview. COSC 304 Introduction to Database Systems. Database Programming. JDBC Interfaces. JDBC Overview

JDBC Drivers Type. JDBC drivers implement the defined interfaces in the JDBC API for interacting with your database server.

G51PGP Programming Paradigms. Lecture 008 Inner classes, anonymous classes, Swing worker thread

DB I. 1 Dr. Ahmed ElShafee, Java course

Chapter 1 GUI Applications

JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling

Module 5 Applets About Applets Hierarchy of Applet Life Cycle of an Applet

Working with Databases and Java

Introduction to SQL & Database Application Development Using Java

NITI NITI I PRIORITET

CSC System Development with Java. Database Connection. Department of Statistics and Computer Science. Budditha Hettige

DataBase Lab JAVA-DATABASE CONNECTION. Eng. Haneen El-masry

CS 120 Fall 2008 Practice Final Exam v1.0m. Name: Model Solution. True/False Section, 20 points: 10 true/false, 2 points each

Discuss setting up JDBC connectivity. Demonstrate a JDBC program Discuss and demonstrate methods associated with JDBC connectivity

ERwin and JDBC. Mar. 6, 2007 Myoung Ho Kim

INTRODUCTION TO JDBC - Revised spring

JDBC Java Database Connectivity is a Java feature that lets you connect

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

SQL in a Server Environment

Questions and Answers. A. A DataSource is the basic service for managing a set of JDBC drivers.

CSCI/CMPE Object-Oriented Programming in Java JDBC. Dongchul Kim. Department of Computer Science University of Texas Rio Grande Valley

Module - 4 Multi-Threaded Programming

Servlet 5.1 JDBC 5.2 JDBC

CSIS 10A PRACTICE FINAL EXAM Name Closed Book Closed Computer 3 Sheets of Notes Allowed

Calling SQL from a host language (Java and Python) Kathleen Durant CS 3200

INTRODUCTION TO JDBC - Revised Spring

User interfaces and Swing

B2.52-R3: INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING THROUGH JAVA

UCLA PIC 20A Java Programming

JDBC. Sun Microsystems has included JDBC API as a part of J2SDK to develop Java applications that can communicate with databases.

COP4540 TUTORIAL PROFESSOR: DR SHU-CHING CHEN TA: H S IN-YU HA

e-pg Pathshala Subject: Computer Science Paper: Web Technology Module: JDBC INTRODUCTION Module No: CS/WT/26 Quadrant 2 e-text

Program 20: //Design an Applet program to handle Mouse Events. import java.awt.*; import java.applet.*; import java.awt.event.*;

Embedded SQL. csc343, Introduction to Databases Diane Horton with examples from Ullman and Widom Fall 2014

OOP Assignment V. For example, the scrolling text (moving banner) problem without a thread looks like:

1. Java is a... language. A. moderate typed B. strogly typed C. weakly typed D. none of these. Answer: B

GUI in Java TalentHome Solutions

Accessing databases in Java using JDBC

Multithread Computing

CMPUT 391 Database Management Systems. JDBC in Review. - Lab 2 -

Pieter van den Hombergh. March 25, 2018

Unit 5 - Exception Handling & Multithreaded

Part I: Stored Procedures. Introduction to SQL Programming Techniques. CSC 375, Fall 2017

Marcin Luckner Warsaw University of Technology Faculty of Mathematics and Information Science

Java application using JDBC to connect to a database.

Le L c e t c ur u e e 7 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Multithreading

Question 1. Show the steps that are involved in sorting the string SORTME using the quicksort algorithm given below.

Server-side Web Programming

Database Application Development

Graphical User Interfaces 2

JRadioButton account_type_radio_button2 = new JRadioButton("Current"); ButtonGroup account_type_button_group = new ButtonGroup();

Java Foundations John Lewis Peter DePasquale Joe Chase Third Edition

GUI DYNAMICS Lecture July 26 CS2110 Summer 2011

Embedded SQL. csc343, Introduction to Databases Renée J. Miller and Fatemeh Nargesian and Sina Meraji Winter 2018

Virtualians.ning.pk. 2 - Java program code is compiled into form called 1. Machine code 2. native Code 3. Byte Code (From Lectuer # 2) 4.

CS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question)

CS506 Web Programming and Development Solved Subjective Questions With Reference For Final Term Lecture No 1

Real SQL Programming 1

Programming in Java

UNIT-3 Java Database Client/Server

CS 556 Distributed Systems

Reading from URL. Intent - open URL get an input stream on the connection, and read from the input stream.

Threads Chate Patanothai

G51PRG: Introduction to Programming Second semester Applets and graphics

Programming Languages and Techniques (CIS120)

Java Database Connectivity (JDBC) 25.1 What is JDBC?

The AWT Event Model 9

CSCI 136 Written Exam #2 Fundamentals of Computer Science II Spring 2015

Multithreading using Java. Dr. Ferdin Joe John Joseph

Java Database Connectivity

Java Applets. Last Time. Java Applets. Java Applets. First Java Applet. Java Applets. v We created our first Java application

Overview. Database Application Development. SQL in Application Code. SQL in Application Code (cont.)

Database Application Development

Database Application Development

WEB SERVICES EXAMPLE 2

CS506 Web Design & Development Final Term Solved MCQs with Reference

This lecture. Databases - JDBC I. Application Programs. Database Access End Users

Transcription:

INTERNAL ASSESSMENT TEST 2 Date : 28-09-15 Max Marks :50 Subject & Code : JAVA&J2EE(10IS753) Section: VII A&B Name of faculty : Mr.Sreenath M V Time : 11.30-1.00 PM Note: Answer any five questions 1) a) Explain the reader- writer problem with a program. 06 class Reader implements Runnable { Q q; Reader(Q q) { this.q = q; new Thread(this, "Reader").start(); public void run() { while(true) { q.read(); class Writer implements Runnable { Q q; Writer(Q q) { this.q = q; new Thread(this, "Writer").start(); public void run() { int i = 0; while(true) { q.write(i++);

class Q { int n; boolean valueset = false; synchronized int read() { if(!valueset) wait(); catch(interruptedexception e) { System.out.println("InterruptedException caught"); System.out.println("read: " + n); valueset = false; notify(); return n; synchronized void write(int n) { if(valueset) wait(); catch(interruptedexception e) { System.out.println("InterruptedException caught"); this.n = n; valueset = true; System.out.println("write: " + n); notify();

class WR { public static void main(string args[]) { Q q = new Q(); new Writer(q); new Reader(q); System.out.println("Press Control-C to stop."); b) What is an adapter class? Demonstrate, with an example. (04M) An adapter class provides an empty implementation of all methods in an event listener interface. Each adapter class implements the corresponding interface with a series of do-nothing methods. For example, MouseListener declares these five methods: public abstract void mouseclicked(mouseevent evt) public abstract void mousepressed(mouseevent evt) public abstract void mousereleased(mouseevent evt) public abstract void mouseentered(mouseevent evt) public abstract void mouseexited(mouseevent evt) Therefore, MouseAdapter looks like this: package java.awt.event; import java.awt.*; import java.awt.event.*; public class MouseAdapter implements MouseListener { public void mouseclicked(mouseevent evt) { public void mousepressed(mouseevent evt) { public void mousereleased(mouseevent evt) { public void mouseentered(mouseevent evt) {

public void mouseexited(mouseevent evt) { By subclassing MouseAdapter rather than implementing MouseListener directly, we can avoid having to write the methods you don't actually need. You only override those that you plan to actually implement. 2) What is transaction processing? Write a program to execute a database transaction. 10 A database transaction consists of a set of SQL statements, each of which must be successfully completed for the transaction to be completed. If one fails, SQL statements that executed successfully up to that point in the transaction must be rolled back. A database transaction isn t completed until the J2EE component calls the commit () method of the Connection object. All SQL statements executed prior to the call to the commit() method can be rolled back. However, once the commit() method is called, none of the SQL statements can be rolled back. The DBMS has an AutoCommit feature that is by default set to true and hence it is not absolutely necessary for any JEE component to call the commit() method. An example //Executing a database transaction String url = "jdbc:odbc:customerinformation"; String userid = "jim"; String password = "keogh"; Statement DataRequest1, DataRequest2; Connection Database; Class.forName ("sun.jdbc.odbc.jdbcodbcdriver"); Database = DriverManager.getConnection (url, userid, password); catch (ClassNotFoundException error) { System.err.println ("Unable to load the JDBC/ODBC bridge." + error);

System.exit (1); catch (SQLException error) { System.err.println ("Cannot connect to the database." + error); System.exit (2); Database.setAutoCommit (false); String query1 = UPDATE Customers SET Street = 5 Main Street + WHERE FirstName = Bob "; String query2 = UPDATE Customers SET Street = 10 Main Street + WHERE FirstName = Tim "; DataRequest1 = Database.createStatement (); DataRequest2 = Database.createStatement (); DataRequest1.executeUpdate (query1); DataRequest2.executeUpdate (query2); Database.commit (); DataRequest1.close(); DataRequest2.close(); Database.close(); catch (SQLException ex) { System.err.println ( SQLException: + ex.getmessage ()); if (Database!= null) { System.err.println ( Transaction is being rolled back ); Database.rollback (); catch (SQLException excep) { System.err.print ( SQLException: ); System.err.println (excep.getmessage ());

3) Explain the scrollable resultset with an example. 10 An example // Using a scrollable virtual cursor String url = "jdbc:odbc:customerinformation"; String userid = "jim"; String password = "keogh"; String printrow; String FirstName; String LastName; Statement DataRequest; ResultSet Results; Connection Db; Class.forName ("sun.jdbc.odbc.jdbcodbcdriver"); Db = DriverManager.getConnection (url, userid, password);

catch (ClassNotFoundException error) { System.err.println ("Unable to load the JDBC/ODBC bridge." + error); System.exit (1); catch (SQLException error) { System.err.println ("Cannot connect to the database." + error); System.exit (2); String query = "SELECT FirstName,LastName FROM Customers"; DataRequest = Db.createStatement (TYPE_SCROLL_INSENSITIVE); Results = DataRequest.executeQuery (query); catch (SQLException error) { System.err.println ("SQL error." + error); System.exit (3); boolean Records = Results.next ();

if (!Records) { System.out.println ("No data returned"); System.exit (4); do { Results.first (); Results.last (); Results.previous (); Results.absolute (10); Results.relative (-2); Results.relative (2); FirstName = Results.getString (1); LastName = Results.getString (2); printrow = FirstName + " " + LastName; System.out.println (printrow); while (Results.next ()); DataRequest.close ();

catch (SQLException error) { System.err.println Data display error." + error); System.exit (5); 4) Explain the mechanism of event delegation model. Give an example for using keyboard event. 10 The Delegation Event model This model defines standard and consistent mechanisms to generate and process events. 1. A source generates an event and sends it to one or more listeners. 2. The listener simply waits until it receives an event. 3. Once an event is received, the listener processes the event and then returns. 4. The advantage of this design is that the application logic that processes events is cleanly separated from the user interface logic that generates those events. 5. A user interface element is able to delegate the processing of an event to a separate piece of code. Using the Delegation Event Model Just follow these steps: 1. Implement the appropriate interface in the listener so that it will receive the type of event desired. 2. Implement the code to register and unregister (if necessary) the listener as a recipient for the event notifications.

Remember that a source may generate several types of events. Each event must be registered separately. Also, an object may register to receive several types of events, but it must implement all of the interfaces that are required to receive these events. // Demonstrate the key event handlers import java.awt.*; import java.awt.event.*; import java.applet.*; /* <applet code="simplekey" width=300 height=100> </applet> */ public class SimpleKey extends Applet implements KeyListener { String msg = ""; int X = 10, Y = 20; // output coordinates public void init () { addkeylistener (this); public void keypressed (KeyEvent ke) { showstatus ("Key Down");

public void keyreleased (KeyEvent ke) { showstatus("key Up"); public void keytyped (KeyEvent ke) { msg += ke.getkeychar (); repaint (); // Display keystrokes public void paint (Graphics g) { g.drawstring (msg, X, Y); 5) Describe the various steps of JDBC process with code snippets. The JDBC process 1. Load the driver 2. Define the connection URL 3. Establish the connection 4. Create a Statement object 5. Execute a query 6. Process the results 7. Close the connection Loading the JDBC driver Before a connection to a database can be established, the JDBC driver for that database must be loaded. Drivers automatically register themselves with the JDBC system when loaded. There are two ways to load a JDBC driver. The first is to specify the driver or colon-separated list of drivers on the command line: 10 > java -Djdbc.drivers=com.company1.Driver:com.company2.Driver MyApp

The second, and recommended method, is to call Class.forName() within the code: // Load the JDBC driver String drivername = "org.gjt.mm.mysql.driver"; Class.forName(driverName); catch (ClassNotFoundException e) { // Could not find the driver Connecting to the DBMS Once our driver is loaded, we can connect to the database. We'll connect via the driver manager class, which selects the appropriate driver for the database we specify. The java.sql.drivermanager class is the highest class in the java.sql hierarchy and is responsible for managing driver information. We identify our database through a URL. No, we're not doing anything on the web in this example - a URL just helps to identify our database. A JDBC URL starts with "jdbc:" This indicates the protocol (JDBC). We also specify our database in the URL. As an example, here's the URL for an ODBC datasource called 'demo'. Our final URL looks like this : jdbc:odbc:demo To connect to the database, we create a string representation of the database. We take the name of the datasource from the command line, and attempt to connect as user "dba", whose password is "sql". // Create a URL that identifies database String url = "jdbc:odbc:" + args[0]; // Now attempt to create a database connection Connection db_connection = DriverManager.getConnection (url, "dba", "sql"); The DriverManager.getConnection() method returns a Connection interface that is used throughout the process to reference the database.

Create and Execute database queries In JDBC, we use a statement object to execute queries. A statement object is responsible for sending the SQL statement, and returning a set of results, if needed, from the query. Statement objects support two main types of statements - an update statement that is normally used for operations which don't generate a response, and a query statement that returns data. // Create a statement to send SQL Statement db_statement = db_connection.createstatement(); Once you have an instance of a statement object, you can call its executeupdate and executequery methods. To illustrate the executeupdate command, we'll create a table that stores information about employees. We'll keep things simple and limit it to name and employee ID. // Create a simple table, which stores an employee ID and name db_statement.executeupdate ("create table employee { int id, char(50) name ;"); // Insert an employee, so the table contains data db_statement.executeupdate ("insert into employee values (1, 'John Doe');"); // Commit changes db_connection.commit(); Now that there's data in the table, we can execute queries. The response to a query will be returned by the executequery method as a ResultSet object. ResultSet objects store the last response to a query for a given statement object. Instances of ResultSet have methods following the pattern of getxx where XX is the name of a data type. Such data types include numbers (bytes, ints, shorts, longs, doubles, big-decimals), as well as strings, booleans, timestamps and binary data. // Execute query ResultSet result = db_statement.executequery ("select * from employee"); // While more rows exist, print them while (result.next() ) { // Use the getint method to obtain emp. id

System.out.println ("ID : " + result.getint("id")); // Use the getstring method to obtain emp. name System.out.println ("Name : " + result.getstring("name")); System.out.println (); Terminate the connection to the DBMS The connection to the DBMS is terminated by using the close() method of the Connection object once the J2EE component is finished accessing the DBMS. 6) What is multithreading? Write a program to create multiple threads in JAVA. // Create multiple threads. class NewThread implements Runnable { String name; // name of thread Thread t; NewThread(String threadname) { name = threadname; t = new Thread(this, name); System.out.println("New thread: " + t); t.start(); // Start the thread // This is the entry point for thread. public void run() { for(int i = 5; i > 0; i--) { System.out.println(name + ": " + i); Thread.sleep(1000); catch (InterruptedException e) { 10

System.out.println(name + "Interrupted"); System.out.println(name + " exiting."); class MultiThreadDemo { public static void main(string args[]) { new NewThread("One"); // start threads new NewThread("Two"); new NewThread("Three"); // wait for other threads to end Thread.sleep(10000); catch (InterruptedException e) { System.out.println("Main thread Interrupted"); System.out.println("Main thread exiting."); * * * * * *