Java/Database SQL JDBC/Database Swing Applet

Материал из Java эксперт
Перейти к: навигация, поиск

Accounts

   <source lang="java">

/* MySQL and Java Developer"s Guide Mark Matthews, Jim Cole, Joseph D. Gradecki Publisher Wiley, Published February 2003, ISBN 0471269239

  • /

import java.awt.Container; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Vector; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; public class Accounts extends JFrame {

 private JButton getAccountButton, insertAccountButton, deleteAccountButton,
     updateAccountButton;
 private JList accountNumberList;
 private Connection connection;
 private JTextField accountIDText, usernameText, passwordText, tsText,
     activeTSText;
 private JTextArea errorText;
 public Accounts() {
   try {
     Class.forName("com.mysql.jdbc.Driver").newInstance();
   } catch (Exception e) {
     System.err.println("Unable to find and load driver");
     System.exit(1);
   }
 }
 private void loadAccounts() {
   Vector v = new Vector();
   try {
     Statement statement = connection.createStatement();
     ResultSet rs = statement.executeQuery("SELECT acc_id FROM acc_acc");
     while (rs.next()) {
       v.addElement(rs.getString("acc_id"));
     }
     rs.close();
   } catch (SQLException e) {
     displaySQLErrors(e);
   }
   accountNumberList.setListData(v);
 }
 private void buildGUI() {
   Container c = getContentPane();
   c.setLayout(new FlowLayout());
   accountNumberList = new JList();
   loadAccounts();
   accountNumberList.setVisibleRowCount(2);
   JScrollPane accountNumberListScrollPane = new JScrollPane(
       accountNumberList);
   //Do Get Account Button
   getAccountButton = new JButton("Get Account");
   getAccountButton.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {
       try {
         Statement statement = connection.createStatement();
         ResultSet rs = statement
             .executeQuery("SELECT * FROM acc_acc WHERE acc_id = "
                 + accountNumberList.getSelectedValue());
         if (rs.next()) {
           accountIDText.setText(rs.getString("acc_id"));
           usernameText.setText(rs.getString("username"));
           passwordText.setText(rs.getString("password"));
           tsText.setText(rs.getString("ts"));
           activeTSText.setText(rs.getString("act_ts"));
         }
       } catch (SQLException selectException) {
         displaySQLErrors(selectException);
       }
     }
   });
   //Do Insert Account Button
   insertAccountButton = new JButton("Insert Account");
   insertAccountButton.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {
       try {
         Statement statement = connection.createStatement();
         int i = statement
             .executeUpdate("INSERT INTO acc_acc VALUES("
                 + accountIDText.getText() + ", " + """
                 + usernameText.getText() + "", " + """
                 + passwordText.getText() + "", " + "0"
                 + ", " + "now())");
         errorText.append("Inserted " + i + " rows successfully");
         accountNumberList.removeAll();
         loadAccounts();
       } catch (SQLException insertException) {
         displaySQLErrors(insertException);
       }
     }
   });
   //Do Delete Account Button
   deleteAccountButton = new JButton("Delete Account");
   deleteAccountButton.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {
       try {
         Statement statement = connection.createStatement();
         int i = statement
             .executeUpdate("DELETE FROM acc_acc WHERE acc_id = "
                 + accountNumberList.getSelectedValue());
         errorText.append("Deleted " + i + " rows successfully");
         accountNumberList.removeAll();
         loadAccounts();
       } catch (SQLException insertException) {
         displaySQLErrors(insertException);
       }
     }
   });
   //Do Update Account Button
   updateAccountButton = new JButton("Update Account");
   updateAccountButton.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {
       try {
         Statement statement = connection.createStatement();
         int i = statement.executeUpdate("UPDATE acc_acc "
             + "SET username="" + usernameText.getText() + "", "
             + "password="" + passwordText.getText() + "", "
             + "act_ts = now() " + "WHERE acc_id = "
             + accountNumberList.getSelectedValue());
         errorText.append("Updated " + i + " rows successfully");
         accountNumberList.removeAll();
         loadAccounts();
       } catch (SQLException insertException) {
         displaySQLErrors(insertException);
       }
     }
   });
   JPanel first = new JPanel(new GridLayout(5, 1));
   first.add(accountNumberListScrollPane);
   first.add(getAccountButton);
   first.add(insertAccountButton);
   first.add(deleteAccountButton);
   first.add(updateAccountButton);
   accountIDText = new JTextField(15);
   usernameText = new JTextField(15);
   passwordText = new JTextField(15);
   tsText = new JTextField(15);
   activeTSText = new JTextField(15);
   errorText = new JTextArea(5, 15);
   errorText.setEditable(false);
   JPanel second = new JPanel();
   second.setLayout(new GridLayout(6, 1));
   second.add(accountIDText);
   second.add(usernameText);
   second.add(passwordText);
   second.add(tsText);
   second.add(activeTSText);
   JPanel third = new JPanel();
   third.add(new JScrollPane(errorText));
   c.add(first);
   c.add(second);
   c.add(third);
   setSize(500, 500);
   show();
 }
 public void connectToDB() {
   try {
     connection = DriverManager
         .getConnection("jdbc:mysql://192.168.1.25/accounts?user=spider&password=spider");
   } catch (SQLException connectException) {
     System.out.println(connectException.getMessage());
     System.out.println(connectException.getSQLState());
     System.out.println(connectException.getErrorCode());
   }
 }
 private void displaySQLErrors(SQLException e) {
   errorText.append("SQLException: " + e.getMessage() + "\n");
   errorText.append("SQLState:     " + e.getSQLState() + "\n");
   errorText.append("VendorError:  " + e.getErrorCode() + "\n");
 }
 private void init() {
   connectToDB();
 }
 public static void main(String[] args) {
   Accounts accounts = new Accounts();
   accounts.addWindowListener(new WindowAdapter() {
     public void windowClosing(WindowEvent e) {
       System.exit(0);
     }
   });
   accounts.init();
   accounts.buildGUI();
 }

}

      </source>
   
  
 
  



Applet and Oracle JDBC

   <source lang="java">

/* Java Programming with Oracle JDBC by Donald Bales ISBN: 059600088X Publisher: O"Reilly

  • /

import java.applet.Applet; import java.awt.Graphics; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; public class TestApplet extends Applet {

 private Connection conn;
 private Timestamp created = new Timestamp(System.currentTimeMillis());
 public void init() {
   try {
     System.out
         .println("init(): loading OracleDriver for applet created at "
             + created.toString());
     Class.forName("oracle.jdbc.driver.OracleDriver");
     System.out.println("init(): getting connection");
     conn = DriverManager.getConnection(
         "jdbc:oracle:thin:@dssw2k01:1521:orcl", "scott", "tiger");
   } catch (ClassNotFoundException e) {
     System.err.println("init(): ClassNotFoundException: "
         + e.getMessage());
   } catch (SQLException e) {
     System.err.println("init(): SQLException: " + e.getMessage());
   }
 }
 public void start() {
   System.out.println("start(): ");
 }
 public void stop() {
   System.out.println("stop(): ");
 }
 public void paint(Graphics g) {
   System.out.println("paint(): querying the database");
   try {
     Statement stmt = conn.createStatement();
     ResultSet rset = stmt
         .executeQuery("select "Hello "||initcap(USER) result from dual");
     while (rset.next())
       g.drawString(rset.getString(1), 10, 10);
     rset.close();
     stmt.close();
   } catch (SQLException e) {
     System.err.println("paint(): SQLException: " + e.getMessage());
   }
 }
 public void destroy() {
   System.out
       .println("destroy(): closing connection for applet created at "
           + created.toString());
   try {
     conn.close();
   } catch (SQLException e) {
     System.err.println("destroy: SQLException: " + e.getMessage());
   }
 }

} //TestApplet.html /* <html> <head> </head> <body> <applet code=TestApplet archive=TestApplet.zip width=100 height=50></applet> </body> </html>

  • /


      </source>
   
  
 
  



Applet JDBC

   <source lang="java">

/* MySQL and Java Developer"s Guide Mark Matthews, Jim Cole, Joseph D. Gradecki Publisher Wiley, Published February 2003, ISBN 0471269239

  • /

import java.awt.BorderLayout; import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Vector; import javax.swing.JApplet; import javax.swing.JButton; import javax.swing.JList; import javax.swing.JScrollPane; public class AppletJDBCDrop extends JApplet implements ActionListener {

 private Connection connection;
 private JList tableList;
 private JButton dropButton;
 public void init() {
   Connection connection;
   try {
     Class.forName("com.mysql.jdbc.Driver").newInstance();
     connection = DriverManager
         .getConnection("jdbc:mysql://192.168.1.25/accounts?user=spider&password=spider");
   } catch (Exception connectException) {
     connectException.printStackTrace();
   }
   Container c = getContentPane();
   tableList = new JList();
   loadTables();
   c.add(new JScrollPane(tableList), BorderLayout.NORTH);
   dropButton = new JButton("Drop Table");
   dropButton.addActionListener(this);
   c.add(dropButton, BorderLayout.SOUTH);
 }
 public void actionPerformed(ActionEvent e) {
   try {
     Statement statement = connection.createStatement();
     ResultSet rs = statement.executeQuery("DROP TABLE "
         + tableList.getSelectedValue());
   } catch (SQLException actionException) {
   }
 }
 private void loadTables() {
   Vector v = new Vector();
   try {
     Statement statement = connection.createStatement();
     ResultSet rs = statement.executeQuery("SHOW TABLES");
     while (rs.next()) {
       v.addElement(rs.getString(1));
     }
     rs.close();
   } catch (SQLException e) {
   }
   v.addElement("acc_acc");
   v.addElement("acc_add");
   v.addElement("junk");
   tableList.setListData(v);
 }

} /* <html> <applet code="Drop.class" width=200 height=200> </applet> </html>

  • /


      </source>
   
  
 
  



Java database and Swing

   <source lang="java">

/* MySQL and Java Developer"s Guide Mark Matthews, Jim Cole, Joseph D. Gradecki Publisher Wiley, Published February 2003, ISBN 0471269239

  • /

import java.awt.Container; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Vector; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; public class RSAccounts extends JFrame {

 private JButton getAccountButton, insertAccountButton, deleteAccountButton,
     updateAccountButton, nextButton, previousButton, lastButton,
     firstButton, gotoButton, freeQueryButton;
 private JList accountNumberList;
 private JTextField accountIDText, usernameText, passwordText, tsText,
     activeTSText, gotoText, freeQueryText;
 private JTextArea errorText;
 private Connection connection;
 private Statement statement;
 private ResultSet rs;
 public RSAccounts() {
   try {
     Class.forName("com.mysql.jdbc.Driver").newInstance();
   } catch (Exception e) {
     System.err.println("Unable to find and load driver");
     System.exit(1);
   }
 }
 private void loadAccounts() {
   Vector v = new Vector();
   try {
     rs = statement.executeQuery("SELECT * FROM acc_acc");
     while (rs.next()) {
       v.addElement(rs.getString("acc_id"));
     }
   } catch (SQLException e) {
     displaySQLErrors(e);
   }
   accountNumberList.setListData(v);
 }
 private void buildGUI() {
   Container c = getContentPane();
   c.setLayout(new FlowLayout());
   accountNumberList = new JList();
   loadAccounts();
   accountNumberList.setVisibleRowCount(2);
   JScrollPane accountNumberListScrollPane = new JScrollPane(
       accountNumberList);
   gotoText = new JTextField(3);
   freeQueryText = new JTextField(40);
   //Do Get Account Button
   getAccountButton = new JButton("Get Account");
   getAccountButton.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {
       try {
         rs.first();
         while (rs.next()) {
           if (rs.getString("acc_id").equals(
               accountNumberList.getSelectedValue()))
             break;
         }
         if (!rs.isAfterLast()) {
           accountIDText.setText(rs.getString("acc_id"));
           usernameText.setText(rs.getString("username"));
           passwordText.setText(rs.getString("password"));
           tsText.setText(rs.getString("ts"));
           activeTSText.setText(rs.getString("act_ts"));
         }
       } catch (SQLException selectException) {
         displaySQLErrors(selectException);
       }
     }
   });
   //Do Insert Account Button
   insertAccountButton = new JButton("Insert Account");
   insertAccountButton.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {
       try {
         Statement statement = connection.createStatement();
         int i = statement
             .executeUpdate("INSERT INTO acc_acc VALUES("
                 + accountIDText.getText() + ", " + """
                 + usernameText.getText() + "", " + """
                 + passwordText.getText() + "", " + "0"
                 + ", " + "now())");
         errorText.append("Inserted " + i + " rows successfully");
         accountNumberList.removeAll();
         loadAccounts();
       } catch (SQLException insertException) {
         displaySQLErrors(insertException);
       }
     }
   });
   //Do Delete Account Button
   deleteAccountButton = new JButton("Delete Account");
   deleteAccountButton.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {
       try {
         Statement statement = connection.createStatement();
         int i = statement
             .executeUpdate("DELETE FROM acc_acc WHERE acc_id = "
                 + accountNumberList.getSelectedValue());
         errorText.append("Deleted " + i + " rows successfully");
         accountNumberList.removeAll();
         loadAccounts();
       } catch (SQLException insertException) {
         displaySQLErrors(insertException);
       }
     }
   });
   //Do Update Account Button
   updateAccountButton = new JButton("Update Account");
   updateAccountButton.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {
       try {
         Statement statement = connection.createStatement();
         int i = statement.executeUpdate("UPDATE acc_acc "
             + "SET username="" + usernameText.getText() + "", "
             + "password="" + passwordText.getText() + "", "
             + "act_ts = now() " + "WHERE acc_id = "
             + accountNumberList.getSelectedValue());
         errorText.append("Updated " + i + " rows successfully");
         accountNumberList.removeAll();
         loadAccounts();
       } catch (SQLException insertException) {
         displaySQLErrors(insertException);
       }
     }
   });
   //Do Next Button
   nextButton = new JButton(">");
   nextButton.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {
       try {
         if (!rs.isLast()) {
           rs.next();
           accountIDText.setText(rs.getString("acc_id"));
           usernameText.setText(rs.getString("username"));
           passwordText.setText(rs.getString("password"));
           tsText.setText(rs.getString("ts"));
           activeTSText.setText(rs.getString("act_ts"));
         }
       } catch (SQLException insertException) {
         displaySQLErrors(insertException);
       }
     }
   });
   //Do Next Button
   previousButton = new JButton("<");
   previousButton.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {
       try {
         if (!rs.isFirst()) {
           rs.previous();
           accountIDText.setText(rs.getString("acc_id"));
           usernameText.setText(rs.getString("username"));
           passwordText.setText(rs.getString("password"));
           tsText.setText(rs.getString("ts"));
           activeTSText.setText(rs.getString("act_ts"));
         }
       } catch (SQLException insertException) {
         displaySQLErrors(insertException);
       }
     }
   });
   //Do last Button
   lastButton = new JButton(">|");
   lastButton.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {
       try {
         rs.last();
         accountIDText.setText(rs.getString("acc_id"));
         usernameText.setText(rs.getString("username"));
         passwordText.setText(rs.getString("password"));
         tsText.setText(rs.getString("ts"));
         activeTSText.setText(rs.getString("act_ts"));
       } catch (SQLException insertException) {
         displaySQLErrors(insertException);
       }
     }
   });
   //Do first Button
   firstButton = new JButton("|<");
   firstButton.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {
       try {
         rs.first();
         accountIDText.setText(rs.getString("acc_id"));
         usernameText.setText(rs.getString("username"));
         passwordText.setText(rs.getString("password"));
         tsText.setText(rs.getString("ts"));
         activeTSText.setText(rs.getString("act_ts"));
       } catch (SQLException insertException) {
         displaySQLErrors(insertException);
       }
     }
   });
   //Do gotoButton
   gotoButton = new JButton("Goto");
   gotoButton.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {
       try {
         rs.absolute(Integer.parseInt(gotoText.getText()));
         accountIDText.setText(rs.getString("acc_id"));
         usernameText.setText(rs.getString("username"));
         passwordText.setText(rs.getString("password"));
         tsText.setText(rs.getString("ts"));
         activeTSText.setText(rs.getString("act_ts"));
       } catch (SQLException insertException) {
         displaySQLErrors(insertException);
       }
     }
   });
   //Do freeQueryButton
   freeQueryButton = new JButton("Execute Query");
   freeQueryButton.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {
       try {
         if (freeQueryText.getText().toUpperCase().indexOf("SELECT") >= 0) {
           rs = statement.executeQuery(freeQueryText.getText());
           if (rs.next()) {
             accountIDText.setText(rs.getString("acc_id"));
             usernameText.setText(rs.getString("username"));
             passwordText.setText(rs.getString("password"));
             tsText.setText(rs.getString("ts"));
             activeTSText.setText(rs.getString("act_ts"));
           }
         } else {
           int i = statement
               .executeUpdate(freeQueryText.getText());
           errorText.append("Rows affected = " + i);
           loadAccounts();
         }
       } catch (SQLException insertException) {
         displaySQLErrors(insertException);
       }
     }
   });
   JPanel first = new JPanel(new GridLayout(5, 1));
   first.add(accountNumberListScrollPane);
   first.add(getAccountButton);
   first.add(insertAccountButton);
   first.add(deleteAccountButton);
   first.add(updateAccountButton);
   accountIDText = new JTextField(15);
   usernameText = new JTextField(15);
   passwordText = new JTextField(15);
   tsText = new JTextField(15);
   activeTSText = new JTextField(15);
   errorText = new JTextArea(5, 15);
   errorText.setEditable(false);
   JPanel second = new JPanel();
   second.setLayout(new GridLayout(6, 1));
   second.add(accountIDText);
   second.add(usernameText);
   second.add(passwordText);
   second.add(tsText);
   second.add(activeTSText);
   JPanel third = new JPanel();
   third.add(new JScrollPane(errorText));
   JPanel fourth = new JPanel();
   fourth.add(firstButton);
   fourth.add(previousButton);
   fourth.add(nextButton);
   fourth.add(lastButton);
   fourth.add(gotoText);
   fourth.add(gotoButton);
   JPanel fifth = new JPanel();
   fifth.add(freeQueryText);
   c.add(first);
   c.add(second);
   c.add(third);
   c.add(fourth);
   c.add(fifth);
   c.add(freeQueryButton);
   setSize(500, 500);
   show();
 }
 public void connectToDB() {
   try {
     connection = DriverManager
         .getConnection("jdbc:mysql://192.168.1.25/accounts?user=spider&password=spider");
     statement = connection.createStatement();
   } catch (SQLException connectException) {
     System.out.println(connectException.getMessage());
     System.out.println(connectException.getSQLState());
     System.out.println(connectException.getErrorCode());
     System.exit(1);
   }
 }
 private void displaySQLErrors(SQLException e) {
   errorText.append("SQLException: " + e.getMessage() + "\n");
   errorText.append("SQLState:     " + e.getSQLState() + "\n");
   errorText.append("VendorError:  " + e.getErrorCode() + "\n");
 }
 private void init() {
   connectToDB();
 }
 public static void main(String[] args) {
   RSAccounts accounts = new RSAccounts();
   accounts.addWindowListener(new WindowAdapter() {
     public void windowClosing(WindowEvent e) {
       System.exit(0);
     }
   });
   accounts.init();
   accounts.buildGUI();
 }

}

      </source>
   
  
 
  



JDBC Applet Policy

   <source lang="java">

/* Java Programming with Oracle JDBC by Donald Bales ISBN: 059600088X Publisher: O"Reilly

  • /

import java.applet.Applet; import java.awt.Graphics; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; public class TestAppletPolicy extends Applet {

 private Connection conn;
 private Timestamp created = new Timestamp(System.currentTimeMillis());
 public void init() {
   System.out.println(getParameter("otherparams"));
   try {
     System.out
         .println("init(): loading OracleDriver for applet created at "
             + created.toString());
     DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
     System.out.println("init(): getting connection");
     conn = DriverManager
         .getConnection("jdbc:oracle:thin:@dssnt01:1521:dssora01",
             "scott", "tiger");
   } catch (SQLException e) {
     System.err.println("init(): SQLException: " + e.getMessage());
   }
 }
 public void start() {
   System.out.println("start(): ");
 }
 public void stop() {
   System.out.println("stop(): ");
 }
 public void paint(Graphics g) {
   System.out.println("paint(): querying the database");
   try {
     Statement stmt = conn.createStatement();
     ResultSet rset = stmt
         .executeQuery("select "Hello "||initcap(USER) result from dual");
     while (rset.next())
       g.drawString(rset.getString(1), 10, 10);
     rset.close();
     stmt.close();
   } catch (SQLException e) {
     System.err.println("paint(): SQLException: " + e.getMessage());
   }
 }
 public void destroy() {
   System.out
       .println("destroy(): closing connection for applet created at "
           + created.toString());
   try {
     conn.close();
   } catch (SQLException e) {
     System.err.println("destroy: SQLException: " + e.getMessage());
   }
 }

}

//File: TestAppletPolicy.html /* <html> <head> <title>Test an Applet"s access to Sockets using Java 2 Policies</title> </head> <body>

<SCRIPT LANGUAGE="JavaScript">

</SCRIPT> <COMMENT> <SCRIPT LANGUAGE="JavaScript1.1">

</SCRIPT> </COMMENT>

<SCRIPT LANGUAGE="JavaScript">

</SCRIPT> <APPLET

code="TestAppletPolicy.class" 
codebase="." 
archive="TestAppletPolicy.zip"
align="baseline" 
height="20"
width="750" 
>

</XMP> <PARAM NAME="java_code" VALUE="TestAppletPolicy.class"> <PARAM NAME="java_codebase" VALUE="."> <PARAM NAME="java_archive" VALUE="TestAppletPolicy.zip"> <PARAM NAME="type" VALUE="application/x-java-applet;version=1.2.2"> <PARAM NAME="scriptable" VALUE="true"> if (_ie == true) document.writeln( "<PARAM NAME="otherparams" VALUE="Applet launched with OBJECT">"); else document.writeln( "<PARAM NAME="otherparams" VALUE="Applet launched with APPLET">"); No JDK 1.2 support for APPLET!! </APPLET> </NOEMBED> </EMBED> </OBJECT> </body> </html>

  • /


      </source>
   
  
 
  



JDBC Applet running in Netscape

   <source lang="java">

/* Java Programming with Oracle JDBC by Donald Bales ISBN: 059600088X Publisher: O"Reilly

  • /

import java.applet.Applet; import java.awt.*; import java.sql.*; import netscape.security.PrivilegeManager; public class TestAppletNetscape extends Applet {

 private Connection conn;
 private Timestamp created = new Timestamp(System.currentTimeMillis());
 public void init() {
   try {
     System.out
         .println("init(): loading OracleDriver for applet created at "
             + created.toString());
     Class.forName("oracle.jdbc.driver.OracleDriver");
     PrivilegeManager.enablePrivilege("UniversalConnect");
     System.out.println("init(): getting connection");
     PrivilegeManager.checkPrivilegeEnabled("UniversalConnect");
     conn = DriverManager
         .getConnection("jdbc:oracle:thin:@dssnt01:1521:dssora01",
             "scott", "tiger");
   } catch (ClassNotFoundException e) {
     System.err.println("init(): ClassNotFoundException: "
         + e.getMessage());
   } catch (SQLException e) {
     System.err.println("init(): SQLException: " + e.getMessage());
   }
 }
 public void start() {
   System.out.println("start(): ");
 }
 public void stop() {
   System.out.println("stop(): ");
 }
 public void paint(Graphics g) {
   System.out.println("paint(): querying the database");
   try {
     PrivilegeManager.enablePrivilege("UniversalConnect");
     Statement stmt = conn.createStatement();
     ResultSet rset = stmt
         .executeQuery("select "Hello "||initcap(USER) result from dual");
     while (rset.next())
       g.drawString(rset.getString(1), 10, 10);
     rset.close();
     stmt.close();
   } catch (SQLException e) {
     System.err.println("paint(): SQLException: " + e.getMessage());
   }
 }
 public void destroy() {
   System.out
       .println("destroy(): closing connection for applet created at "
           + created.toString());
   try {
     conn.close();
   } catch (SQLException e) {
     System.err.println("destroy: SQLException: " + e.getMessage());
   }
 }

}

//File: TestAppletNestscape.html /* <html> <head> </head> <body> <applet codebase="." code="TestAppletNetscape.class" archive="TestAppletNetscape.zip" width=750 height=20></applet> </body> </html>

  • /
      </source>
   
  
 
  



RowSet Model based on TableModel (JTable)

   <source lang="java">

/* Database Programming with JDBC and Java, Second Edition By George Reese ISBN: 1-56592-616-1 Publisher: O"Reilly

  • /

/* $Id: RowSetModel.java,v 1.1 1999/03/03 06:00:22 borg Exp $ */ /* Copyright 1999 George Reese, All Rights Reserved */ import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Types; import javax.sql.RowSet; import javax.sql.RowSetEvent; import javax.sql.RowSetListener; import javax.swing.table.AbstractTableModel; public class RowSetModel extends AbstractTableModel implements RowSetListener {

 private RowSet rowSet = null;
 public RowSetModel(RowSet set) {
   super();
   rowSet = set;
   rowSet.addRowSetListener(this);
 }
 public void cursorMoved(RowSetEvent event) {
 }
 public Class getColumnClass(int column) {
   String cname;
   int type;
   try {
     ResultSetMetaData meta = rowSet.getMetaData();
     if (meta == null) {
       return null;
     }
     type = meta.getColumnType(column + 1);
   } catch (SQLException e) {
     e.printStackTrace();
     return super.getColumnClass(column);
   }
   switch (type) {
   case Types.BIT: {
     cname = "java.lang.Boolean";
     break;
   }
   case Types.TINYINT: {
     cname = "java.lang.Byte";
     break;
   }
   case Types.SMALLINT: {
     cname = "java.lang.Short";
     break;
   }
   case Types.INTEGER: {
     cname = "java.lang.Integer";
     break;
   }
   case Types.BIGINT: {
     cname = "java.lang.Long";
     break;
   }
   case Types.FLOAT:
   case Types.REAL: {
     cname = "java.lang.Float";
     break;
   }
   case Types.DOUBLE: {
     cname = "java.lang.Double";
     break;
   }
   case Types.NUMERIC: {
     cname = "java.lang.Number";
     break;
   }
   case Types.DECIMAL: {
     cname = "java.math.BigDecimal";
     break;
   }
   case Types.CHAR:
   case Types.VARCHAR:
   case Types.LONGVARCHAR: {
     cname = "java.lang.String";
     break;
   }
   case Types.DATE: {
     cname = "java.sql.Date";
     break;
   }
   case Types.TIME: {
     cname = "java.sql.Time";
     break;
   }
   case Types.TIMESTAMP: {
     cname = "java.sql.Timestamp";
     break;
   }
   case Types.BINARY:
   case Types.VARBINARY:
   case Types.LONGVARBINARY: {
     cname = "byte[]";
     break;
   }
   case Types.OTHER:
   case Types.JAVA_OBJECT: {
     cname = "java.lang.Object";
     break;
   }
   case Types.CLOB: {
     cname = "java.sql.Clob";
     break;
   }
   case Types.BLOB: {
     cname = "java.ssql.Blob";
     break;
   }
   case Types.REF: {
     cname = "java.sql.Ref";
     break;
   }
   case Types.STRUCT: {
     cname = "java.sql.Struct";
     break;
   }
   default: {
     return super.getColumnClass(column);
   }
   }
   try {
     return Class.forName(cname);
   } catch (Exception e) {
     e.printStackTrace();
     return super.getColumnClass(column);
   }
 }
 public int getColumnCount() {
   try {
     ResultSetMetaData meta = rowSet.getMetaData();
     if (meta == null) {
       return 0;
     }
     return meta.getColumnCount();
   } catch (SQLException e) {
     return 0;
   }
 }
 public String getColumnName(int col) {
   try {
     ResultSetMetaData meta = rowSet.getMetaData();
     if (meta == null) {
       return null;
     }
     return meta.getColumnName(col + 1);
   } catch (SQLException e) {
     return "Error";
   }
 }
 public int getRowCount() {
   try {
     if (rowSet.last()) {
       return (rowSet.getRow());
     } else {
       return 0;
     }
   } catch (SQLException e) {
     return 0;
   }
 }
 public Object getValueAt(int row, int col) {
   try {
     if (!rowSet.absolute(row + 1)) {
       return null;
     }
     return rowSet.getObject(col + 1);
   } catch (SQLException e) {
     return null;
   }
 }
 public void rowChanged(RowSetEvent event) {
   try {
     int row = rowSet.getRow();
     if (rowSet.rowDeleted()) {
       fireTableRowsDeleted(row, row);
     } else if (rowSet.rowInserted()) {
       fireTableRowsInserted(row, row);
     } else if (rowSet.rowUpdated()) {
       fireTableRowsUpdated(row, row);
     }
   } catch (SQLException e) {
   }
 }
 public void rowSetChanged(RowSetEvent event) {
   fireTableStructureChanged();
 }
 public void setValueAt(Object value, int row, int column) {
   try {
     if (!rowSet.absolute(row + 1)) {
       return;
     }
     rowSet.updateObject(column + 1, value);
   } catch (SQLException e) {
   }
 }

}

      </source>
   
  
 
  



This is a demonstration JDBC applet

   <source lang="java">

/* Copyright 2003 Sun Microsystems, Inc. ALL RIGHTS RESERVED. Use of this software is authorized pursuant to the terms of the license found at http://developer.java.sun.ru/berkeley_license.html. Copyright 2003 Sun Microsystems, Inc. All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistribution of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistribution in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of Sun Microsystems, Inc. or the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission. This software is provided "AS IS," without a warranty of any kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICORSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. You acknowledge that this software is not designed, licensed or intended for use in the design, construction, operation or maintenance of any nuclear facility.

  • /

/*

* Copyright 2003 Sun Microsystems, Inc.  ALL RIGHTS RESERVED.
* Use of this software is authorized pursuant to the terms of the license found at
* http://developer.java.sun.ru/berkeley_license.html.
*/ 

/**

* This is a demonstration JDBC applet.
* It displays some simple standard output from the Coffee database.
*/

import java.applet.Applet; import java.awt.Graphics; import java.util.Vector; import java.sql.*; public class OutputApplet extends Applet implements Runnable {

   private Thread worker;
   private Vector queryResults;
   private String message = "Initializing";
   public synchronized void start() {
 // Every time "start" is called we create a worker thread to
 // re-evaluate the database query.
 if (worker == null) {  
     message = "Connecting to database";
           worker = new Thread(this);
     worker.start();
 }
   }
   /**
    * The "run" method is called from the worker thread.  Notice that
    * because this method is doing potentially slow databases accesses
    * we avoid making it a synchronized method.
    */
   public void run() {
 String url = "jdbc:mySubprotocol:myDataSource";
 String query = "select COF_NAME, PRICE from COFFEES";
 
 try {
     Class.forName("myDriver.ClassName");
 } catch(Exception ex) {
     setError("Can"t find Database driver class: " + ex);
     return;
 }
 try {
     Vector results = new Vector();
     Connection con = DriverManager.getConnection(url,
           "myLogin", "myPassword");
     Statement stmt = con.createStatement();
     ResultSet rs = stmt.executeQuery(query);
     while (rs.next()) {
   String s = rs.getString("COF_NAME");
   float f = rs.getFloat("PRICE");
   String text = s + "     " + f;
   results.addElement(text);
     }
     stmt.close();
     con.close();
     setResults(results);
 } catch(SQLException ex) {
     setError("SQLException: " + ex);
 }
   }
   /**
    * The "paint" method is called by AWT when it wants us to
    * display our current state on the screen.
    */
   public synchronized void paint(Graphics g) {
 // If there are no results available, display the current message.
 if (queryResults == null) {
     g.drawString(message, 5, 50);
     return;
 }
 // Display the results.
 g.drawString("Prices of coffee per pound:  ", 5, 10);
 int y = 30;
 java.util.Enumeration enum = queryResults.elements();
 while (enum.hasMoreElements()) {
     String text = (String)enum.nextElement();
     g.drawString(text, 5, y);
     y = y + 15;
 }
   }
   /**
    * This private method is used to record an error message for
    * later display.
    */
   private synchronized void setError(String mess) {
 queryResults = null;  
 message = mess;  
 worker = null;
 // And ask AWT to repaint this applet.
 repaint();
   }
   /**
    * This private method is used to record the results of a query, for
    * later display.
    */
   private synchronized void setResults(Vector results) {
 queryResults = results;
 worker = null;
 // And ask AWT to repaint this applet.
 repaint();
   }

}


      </source>