Oop Java Unit 5
Oop Java Unit 5
applet1.html
<html>
<applet code="SimpleApplet" width=200 height=60>
</applet>
</html>
Syntax of Applet tag in HTML
< APPLET
[CODEBASE = codebaseURL]
CODE = appletFile
[ALT = alternateText]
[NAME = appletInstanceName] WIDTH = pixels HEIGHT = pixels
[ALIGN = alignment]
[VSPACE = pixels] [HSPACE = pixels]
>
[< PARAM NAME = AttributeName VALUE = AttributeValue>] [<
PARAM NAME = AttributeName2 VALUE = AttributeValue>]
...
[HTML Displayed in the absence of Java]
</APPLET>
Life cycle of an applet
• Applet is initialized.
– public void init(): is used to initialized the
Applet. It is invoked only once.
• Applet is started.
– public void start(): is invoked after the init()
method or browser is maximized. It is used to
start the Applet.
• Applet is painted.
– public void paint(Graphics g): is used to paint
the Applet. It provides Graphics class object that
can be used for drawing oval, rectangle, arc etc.
• Applet is stopped.
– public void stop(): is used to stop the Applet. It
is invoked when Applet is stop or browser is
minimized.
• Applet is destroyed.
– public void destroy(): is used to destroy the
Applet. It is invoked only once.
Life cycle of an applet
import java.awt.*;
import java.applet.*;
/*
<applet code="AppletLifeCycle" width=200 height=60>
</applet>
*/
public class AppletLifeCycle extends Applet
{
public void init()
{
setBackground(Color.CYAN);
System.out.println("init() called");
}
public void start()
{
System.out.println("Start() called");
}
public void paint(Graphics g)
{
System.out.println("Paint() called");
}
public void stop()
{
System.out.println("Stop() Called");
}
public void destroy()
{
System.out.println("Destroy() Called");
}
}
showStatus(String msg)
In addition to displaying information in its window, an
applet can also output a message to the status window
of the browser or applet viewer on which it is running.
To do so, call showStatus( ) with the string that you want
displayed.
The status window is a good place to give the user
feedback about what is occurring in the applet, suggest
options, or possibly report some types of errors.
The status window also makes an excellent debugging
aid, because it gives you an easy way to output
information about your applet.
showStatus(String msg)
l2=new JLabel(i);
l2.setBounds(50,100, 300,100);
f.add(l1); f.add(l2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}
JButton
public class JButton extends AbstractButton implements Accessible
Constructor Description
Constructor Description
b1.addActionListener(this);
b2.addActionListener(this);
f.add(tf1);f.add(tf2);f.add(tf3);f.add(b1);f.add(b2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String s1=tf1.getText();
String s2=tf2.getText();
int a=Integer.parseInt(s1);
int b=Integer.parseInt(s2);
int c=0;
if(e.getSource()==b1){
c=a+b;
}else if(e.getSource()==b2){
c=a-b;
}
String result=String.valueOf(c);
tf3.setText(result);
}
public static void main(String[] args) {
new TextFieldExample();
}
}
JTextArea
The object of a JTextArea class is a multi line region that displays text. It allows the
editing of multiple line text. It inherits JTextComponent class
Constructor Description
JTextArea() Creates a text area that displays no text initially.
JTextArea(String s) Creates a text area that displays specified text
initially.
JTextArea(int row, int column) Creates a text area with the specified number of
rows and columns that displays no text initially.
JTextArea(String s, int row, int column) Creates a text area with the specified number of
rows and columns that displays specified text.
Methods Description
void setRows(int rows) It is used to set specified number of rows.
void setColumns(int cols) It is used to set specified number of
columns.
void setFont(Font f) It is used to set the specified font.
void insert(String s, int position) It is used to insert the specified text on the
specified position.
void append(String s) It is used to append the given text to the
end of the document.
import javax.swing.*; Example-1
public class TextAreaExample
{
TextAreaExample(){
JFrame f= new JFrame();
JTextArea area=new JTextArea("Welcome to Ravindra College of Engineering”);
area.setBounds(10,30, 200,200);
f.add(area);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new TextAreaExample();
}}
import javax.swing.*; Example-2
import java.awt.event.*;
public class TextAreaExample implements ActionListener{
JLabel l1,l2;
JTextArea area;
JButton b;
TextAreaExample() {
JFrame f= new JFrame();
l1=new JLabel();
l1.setBounds(50,25,100,30);
l2=new JLabel();
l2.setBounds(160,25,100,30);
area=new JTextArea();
area.setBounds(20,75,250,200);
b=new JButton("Count Words");
b.setBounds(100,300,120,30);
b.addActionListener(this);
f.add(l1);f.add(l2);f.add(area);f.add(b);
f.setSize(450,450);
f.setLayout(null);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e){
String text=area.getText();
String words[]=text.split("\\s");
l1.setText("Words: "+words.length);
l2.setText("Characters: "+text.length());
}
public static void main(String[] args) {
new TextAreaExample();
}
}
JPasswordField
The object of a JPasswordField class is a text component specialized for password
entry. It allows the editing of a single line of text. It inherits JTextField class.
import javax.swing.*;
public class PasswordFieldExample {
public static void main(String[] args) {
JFrame f=new JFrame("Password Field Example");
JPasswordField value = new JPasswordField();
JLabel l1=new JLabel("Password:");
l1.setBounds(20,100, 80,30);
value.setBounds(100,100,100,30);
f.add(value); f.add(l1);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}
JCheckBox
The JCheckBox class is used to create a checkbox. It is used to turn an option on (true) or off
(false). Clicking on a CheckBox changes its state from "on" to "off" or from "off" to "on ".It
inherits JToggleButton class.
Methods Description
AccessibleContext It is used to get the AccessibleContext
getAccessibleContext() associated with this JCheckBox.
protected String paramString() It returns a string representation of this
JCheckBox.
import javax.swing.*;
public class CheckBoxExample
{
CheckBoxExample(){
JFrame f= new JFrame("CheckBox Example");
JCheckBox checkBox1 = new JCheckBox("C++");
checkBox1.setBounds(100,100, 50,50);
JCheckBox checkBox2 = new JCheckBox("Java", true);
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1);
f.add(checkBox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckBoxExample();
}}
JCheckBox
checkbox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
JCheckBox cb = (JCheckBox) event.getSource();
if (cb.isSelected()) {
// do something if check box is selected
} else {
// check box is unselected, do something else
}
}
});
JRadioButton
The JRadioButton class is used to create a radio button. It is used to choose one option from
multiple options. It is widely used in exam systems or quiz.
It should be added in ButtonGroup to select one radio button only.
Constructor Description
JRadioButton() Creates an unselected radio button with no text.
JRadioButton(String s) Creates an unselected radio button with specified text.
JRadioButton(String s, boolean selected) Creates a radio button with the specified text and
selected status.
Methods Description
void setText(String s) It is used to set specified text on button.
String getText() It is used to return the text of the button.
void setEnabled(boolean b) It is used to enable or disable the button.
void setIcon(Icon b) It is used to set the specified Icon on the button.
Icon getIcon() It is used to get the Icon of the button.
void setMnemonic(int a) It is used to set the mnemonic on the button.
void addActionListener(ActionListener a) It is used to add the action listener to this object.
import javax.swing.*; Example-1
public class RadioButtonExample {
JFrame f;
RadioButtonExample(){
f=new JFrame();
JRadioButton r1=new JRadioButton("A) Male");
JRadioButton r2=new JRadioButton("B) Female");
r1.setBounds(75,50,100,30);
r2.setBounds(75,100,100,30);
ButtonGroup bg=new ButtonGroup();
bg.add(r1);bg.add(r2);
f.add(r1);f.add(r2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args) {
new RadioButtonExample();
}
}
import javax.swing.*; Example-2
import java.awt.event.*;
class RadioButtonExample extends JFrame implements ActionListener{
JRadioButton rb1,rb2;
JButton b;
RadioButtonExample(){
rb1=new JRadioButton("Male");
rb1.setBounds(100,50,100,30);
rb2=new JRadioButton("Female");
rb2.setBounds(100,100,100,30);
ButtonGroup bg=new ButtonGroup();
bg.add(rb1);bg.add(rb2);
b=new JButton("click");
b.setBounds(100,150,80,30);
b.addActionListener(this);
add(rb1);add(rb2);add(b);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
if(rb1.isSelected()){
JOptionPane.showMessageDialog(this,"You are Male.");
}
if(rb2.isSelected()){
JOptionPane.showMessageDialog(this,"You are Female.");
}
}
public static void main(String args[]){
new RadioButtonExample();
}}
JComboBox
The object of Choice class is used to show popup menu of choices. Choice selected by user
is shown on the top of a menu. It inherits JComponent class.
Methods Description
void addItem(Object anObject) It is used to add an item to the item list.
void removeItem(Object anObject) It is used to delete an item to the item list.
void removeAllItems() It is used to remove all the items from the
list.
void setEditable(boolean b) It is used to determine whether the
JComboBox is editable.
void addActionListener(ActionListener a) It is used to add the ActionListener.
void addItemListener(ItemListener i) It is used to add the ItemListener.
import javax.swing.*;
public class ComboBoxExample {
JFrame f;
ComboBoxExample(){
f=new JFrame("ComboBox Example");
String country[]={"India","Aus","U.S.A","England","Newzealand"};
Constructor Description
JList() Creates a JList with an empty, read-only, model.
JList(ary[] listData) Creates a JList that displays the elements in the
specified array.
JList(ListModel<ary> dataModel) Creates a JList that displays elements from the
specified, non-null, model.
Methods Description
Void It is used to add a listener to the list, to be
addListSelectionListener(ListSelectionListen notified each time a change to the selection
er listener) occurs.
int getSelectedIndex() It is used to return the smallest selected cell
index.
ListModel getModel() It is used to return the data model that holds a
list of items displayed by the JList component.
void setListData(Object[] listData) It is used to create a read-only ListModel from
an array of objects.
import javax.swing.*;
public class ListExample
{
ListExample(){
JFrame f= new JFrame();
DefaultListModel<String> l1 = new DefaultListModel<>();
l1.addElement("Item1");
l1.addElement("Item2");
l1.addElement("Item3");
l1.addElement("Item4");
JList<String> list = new JList<>(l1);
list.setBounds(100,100, 75,75);
f.add(list);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new ListExample();
}}
JTable
The JTable class is used to display data in tabular form. It is composed of rows and columns.
Constructor Description
JTable() Creates a table with empty cells.
JTable(Object[][] rows, Object[] Creates a table with the specified data.
columns)
import javax.swing.*;
public class TableExample {
JFrame f;
TableExample(){
f=new JFrame();
String data[][]={ {"101","Amit","670000"},
{"102","Jai","780000"},
{"101","Sachin","700000"}};
String column[]={"ID","NAME","SALARY"};
JTable jt=new JTable(data,column);
jt.setBounds(30,40,200,300);
JScrollPane sp=new JScrollPane(jt);
f.add(sp);
f.setSize(300,400);
f.setVisible(true);
}
public static void main(String[] args) {
new TableExample();
}
}
Java™:
The Complete Reference
UNIT – 5 & Chapter – 29
Constructor Description
JTree() Creates a JTree with a sample model.
JTree(Object[] value) Creates a JTree with every element of the
specified array as the child of a new root node.
JTree(TreeNode root) Creates a JTree with the specified TreeNode as
its root, which displays the root node.
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
public class TreeExample {
JFrame f;
TreeExample(){
f=new JFrame();
DefaultMutableTreeNode style=new DefaultMutableTreeNode("Style");
DefaultMutableTreeNode color=new DefaultMutableTreeNode("color");
DefaultMutableTreeNode font=new DefaultMutableTreeNode("font");
style.add(color);
style.add(font);
DefaultMutableTreeNode red=new DefaultMutableTreeNode("red");
DefaultMutableTreeNode blue=new DefaultMutableTreeNode("blue");
DefaultMutableTreeNode black=new DefaultMutableTreeNode("black");
DefaultMutableTreeNode green=new DefaultMutableTreeNode("green");
color.add(red); color.add(blue); color.add(black); color.add(green);
JTree jt=new JTree(style);
f.add(jt);
f.setSize(200,200);
f.setVisible(true);
}
public static void main(String[] args) {
new TreeExample();
}}
JMenuBar
The JMenuBar class is used to display menubar on the window or frame. It may have several
menus.
The object of JMenu class is a pull down menu component which is displayed from the
menu bar. It inherits the JMenuItem class.
The object of JMenuItem class adds a simple labeled menu item. The items used in a menu
must belong to the JMenuItem or any of its subclass.
Constructor Description
JDialog() It is used to create a modeless dialog
without a title and without a specified
Frame owner.
JDialog(Frame owner) It is used to create a modeless dialog
with specified Frame as its owner and an
empty title.
JDialog(Frame owner, String title, It is used to create a dialog with the
boolean modal) specified title, owner Frame and modality.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DialogExample {
private static JDialog d;
DialogExample() {
JFrame f= new JFrame();
d = new JDialog(f , "Dialog Example", true);
d.setLayout( new FlowLayout() );
JButton b = new JButton ("OK");
b.addActionListener ( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
DialogExample.d.setVisible(false);
}
});
d.add( new JLabel ("Click button to continue."));
d.add(b);
d.setSize(300,300);
d.setVisible(true);
}
public static void main(String args[])
{
new DialogExample();
} }
LayoutManager
The LayoutManagers are used to arrange components
in a particular manner.
LayoutManager is an interface that is implemented by
all the classes of layout managers.
There are following classes that represents the layout
managers:
1.java.awt.BorderLayout
2.java.awt.FlowLayout
3.java.awt.GridLayout
4.java.awt.CardLayout
5.java.awt.GridBagLayout
6.javax.swing.BoxLayout
7.javax.swing.GroupLayout
8.javax.swing.ScrollPaneLayout
9.javax.swing.SpringLayout etc.
BorderLayout
The BorderLayout is used to arrange the components in
five regions: north, south, east, west and center.
Each region (area) may contain one component only.
It is the default layout of frame or window.
The BorderLayout provides five constants for each
region:
1.public static final int NORTH
2.public static final int SOUTH
3.public static final int EAST
4.public static final int WEST
5.public static final int CENTER
import java.awt.*;
import javax.swing.*;
public class Border {
JFrame f;
Border(){
f=new JFrame();
f.add(b1,BorderLayout.NORTH);
f.add(b2,BorderLayout.SOUTH);
f.add(b3,BorderLayout.EAST);
f.add(b4,BorderLayout.WEST);
f.add(b5,BorderLayout.CENTER);
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new Border();}}
GridLayout
The GridLayout is used to arrange the components in
rectangular grid. One component is displayed in each
rectangle.
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);f.add(b6);f.add(b7);f.add(b8);f.add(b9);
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
f.setLayout(new FlowLayout(FlowLayout.RIGHT));
//setting flow layout of right alignment
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new MyFlowLayout();}}
BoxLayout
The BoxLayout is used to arrange the components
either vertically or horizontally. For this purpose,
BoxLayout provides four constants. They are as follows:
public BoxLayoutExample1 () {
buttons = new Button [5];
public BoxLayoutExample2() {
buttons = new Button [5];
c=getContentPane();
card=new CardLayout(40,30); //cardLayout object with 40 hor and 30 ver space
c.setLayout(card);
b1=new JButton("Apple");
b2=new JButton("Boy");
b3=new JButton("Cat");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
c.add("a",b1);c.add("b",b2);c.add("c",b3);
}
public void actionPerformed(ActionEvent e) {
card.next(c);
}
When adding components, you will use these constants with the
following form of add( ), which is defined by Container:
void add(Component compObj, Object region)
Here, compObj is the component to be added, and region specifies
where the component will be added.
public BoxLayoutEx () {
buttons = new Button [5];
• Methods are
boolean getState( )
void setState(boolean checked)
MenuItem add(MenuItem item)
Menu add(Menu menu)
Object getItem( )
FileDialog(Frame parent)
FileDialog(Frame parent, String boxName)
FileDialog(Frame parent, String boxName, int how)
• FileDialog provides methods that allow you to determine the name of
the file and its path as selected by the user. Here are two examples:
String getDirectory( )
String getFile( )
f.add(panel);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[]) {
new PanelExample();
}
}
Window
• The Window class creates a top-level window.
• A top-level window is not contained within any
other object; it sits directly on the desktop.
• Generally, you won’t create Window objects
directly. Instead, you will use a subclass of
Window called Frame.
• The window is the container that have no borders
and menu bars.
• You must use frame, dialog or another window for
creating a window.
RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
Frame
• The Frame is the container that contain title bar and
can have menu bars. It can have other components
like button, textfield etc.
• It is a subclass of Window and has a title bar, menu
bar, borders, and resizing corners.
• If you create a Frame object from within an applet, it
will contain a warning message, such as “Java Applet
Window,” to the user that an applet window has been
created. This message warns users that the window
they see was started by an applet and not by software
running on their computer.
• When a Frame window is created by a stand-alone
application rather than an applet, a normal window is
created. RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
Canvas
• It is not part of the hierarchy for applet or frame
windows, there is one other type of window that
you will find valuable: Canvas.
• Canvas encapsulates a blank window upon which
you can draw.
ActionEvent ActionListener
MouseEvent MouseListener and MouseMotionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
Registration Methods
For registering the component with the Listener, many classes provide the
registration methods. For example:
• Button
– public void addActionListener(ActionListener a){}
• MenuItem
– public void addActionListener(ActionListener a){}
• TextField
– public void addActionListener(ActionListener a){}
– public void addTextListener(TextListener a){}
• TextArea
– public void addTextListener(TextListener a){}
• Checkbox
– public void addItemListener(ItemListener a){}
• Choice
– public void addItemListener(ItemListener a){}
• List
– public void addActionListener(ActionListener a){}
– public void addItemListener(ItemListener a){}
RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
Steps involved in event handling
• The User clicks the button and the event is
generated.
• Now the object of concerned event class is created
automatically and information about the source
and the event get populated with in same object.
• Event object is forwarded to the method of
registered listener class.
• the method is now get executed and returns.
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
public static void main(String args[]){
new AEvent();
}
}
Mouse Events
}
}
}
Handling Events in a Frame Window
public AppWindowKeyEvnt() {
addKeyListener(new MyKeyAdapter(this));
addWindowListener(new MyWindowAdapter());
}
public void paint(Graphics g) {
g.drawString(keymsg, 10, 40);
}
// Create the window.
public static void main(String args[]) {
AppWindowKeyEvnt appwin = new AppWindowKeyEvnt();
appwin.setSize(new Dimension(300, 200));
appwin.setTitle("An AWT-Based Application");
appwin.setVisible(true);
}
}
class MyKeyAdapter extends KeyAdapter {
AppWindowKeyEvnt appWindow;
public MyKeyAdapter(AppWindowKeyEvnt appWindow) {
this.appWindow = appWindow;
}
public void keyTyped(KeyEvent ke) {
appWindow.keymsg += ke.getKeyChar();
appWindow.repaint();
}
}
class MyWindowAdapter extends WindowAdapter {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
}
// Program – 2 Create an AWT-based application – Mouse Event.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
// Create a frame window.
public class AppWindowMouseEvnt extends Frame {
String mousemsg = "";
int mouseX=30, mouseY=30;
public AppWindowMouseEvnt() {
addMouseListener(new MyMouseAdapter(this));
addWindowListener(new MyWindowAdapter());
}
public void paint(Graphics g) {
g.drawString(mousemsg, mouseX, mouseY);
}
// Create the window.
public static void main(String args[]) {
AppWindowMouseEvnt appwin = new AppWindowMouseEvnt();
appwin.setSize(new Dimension(300, 200));
appwin.setTitle("An AWT-Based Application");
appwin.setVisible(true);
}
}
class MyMouseAdapter extends MouseAdapter {
AppWindowMouseEvnt appWindow;
public MyMouseAdapter(AppWindowMouseEvnt appWindow) {
this.appWindow = appWindow;
}
public void mousePressed(MouseEvent me) {
appWindow.mouseX = me.getX();
appWindow.mouseY = me.getY();
appWindow.mousemsg = "Mouse Down at " + appWindow.mouseX +
", " + appWindow.mouseY;
appWindow.repaint();
}
}
class MyWindowAdapter extends WindowAdapter {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
}
Displaying Information Within a
Window
• A window is a container for information.
Although we have already output small
amounts of text to a window in the preceding
examples.
• Java’s text-handling, graphics-handling, and
font-handling.
Mahesh K
st.close();
con.close();
}
Methods of Statement object
• executeUpdate()
– Used to execute DDL (CREATE, ALTER, and DROP).
DML (INSERT, DELETE, UPDATE, etc) and DCL
statements
– The return value of this method is the number of
rows affected.
• executeQuery()
– Used to execute DQL statements such as SELECT.
– DQL statements only read data from database
tables.
– The return value of this method is a set of rows,
represented as a ResultSet object.
st.close();
con.close();
}
catch(SQLException ex)
{
ex.printStackTrace();
}
catch(ClassNotFoundException cnfe)
{
System.exit(1);
}
}
}
import java.sql.*;
import java.io.*; Example-insert
class IncorrectChoiceException extends Exception
{}
public class InsertTable {
public static void main(String args[])throws ClassNotFoundException, IOException
{
int i = 0;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:dsn");
Statement st = con.createStatement();
boolean wantMore = true;
while(wantMore) {
System.out.print("Enter employee number : ");
int eno = Integer.parseInt(br.readLine());
System.out.print("Enter name : ");
String ename = br.readLine();
System.out.print("Enter salary : ");
double sal = Double.parseDouble(br.readLine());
i += st.executeUpdate("insert into employee values(" + eno + ", \'" + ename + "\'," + sal + ")");
if(choice.equals("N") || choice.equals("n"))
wantMore = false;
else if(choice.equals("Y") || choice.equals("y"))
wantMore = true;
else throw new IncorrectChoiceException();
}
System.out.println("Update success : "+i+" rows updated");
st.close();
con.close();
}catch(SQLException se){
se.printStackTrace();
}catch(IncorrectChoiceException ic)
{
System.out.println("Error : Incorrect choice");
}
finally{
System.out.println("Total updates performed : "+i);
}
}
}
import java.sql.*; Example-update
import java.io.*;
public class UpdateTable {
public static void main(String s[ ]) {
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:dsn");
Statement st=con.createStatement();
con.setAutoCommit(false);
con.commit();
con.close();
}
catch(Exception e)
{
//con.RollBack();
e.printStackTrace();
}
}
}
import java.sql.*; Example-prepared
import java.io.*;
public class PreparedStmts {
public static void main(String s[]) {
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:dsn");
while(true)
{
System.out.println("Enter empno:");
int empno=Integer.parseInt(b.readLine());
if(empno==0)
break;
ps.setInt(1,empno);
ResultSet rs=ps.executeQuery();
while(rs.next())
{
System.out.println("ENAME: "+rs.getString(2));
System.out.println("SALARY: "+rs.getString(3));
}
rs.close();
}
con.close();
}
catch(Exception e)
{
System.out.println("The Exception is...."+e);
}
}
}
END