//DbDemo.java //Demonstrates basic JDBC //I have an access ODBC connection called pets //You will need to make an ODBC connection to run this program //It will not run correctly from the CD without an ODBC source import java.sql.*; import java.io.*; import java.awt.*; import java.awt.event.*; import sun.jdbc.odbc.*; public class DbDemo extends Frame{ TextArea txtOutput = new TextArea(); EventHandler evt = new EventHandler(); TextField txtInput = new TextField("SELECT * FROM pets"); ResultSet rs; Statement stmt; public static void main(String args[]){ DbDemo dd = new DbDemo(); } // end main public DbDemo(){ super("JDBC Demonstration"); setLayout(new BorderLayout()); add(txtOutput, BorderLayout.CENTER); txtOutput.setText("Type \tName \tNotes \n"); add(txtInput, BorderLayout.SOUTH); setSize(300,300); setVisible(true); addWindowListener(evt); txtInput.addActionListener(evt); try{ new JdbcOdbcDriver(); //prepare the connection parameters String url = "jdbc:odbc:pets"; String user = ""; String password = ""; //make the connection Connection con = DriverManager.getConnection(url, user, password); //generate a statement object stmt = con.createStatement(); //create the table //note that this is commented out after the first run //stmt.executeUpdate("CREATE TABLE pets (ID integer, Name VarChar(20), Notes Varchar(20))"); //populate it with some data //stmt.executeUpdate("INSERT INTO pets VALUES (7, 'Walrus', 'Dorothy', 'Eats goldfish'); //generate a query rs = stmt.executeQuery("SELECT * FROM pets"); while (rs.next()){ txtOutput.append(rs.getString("Type") + "\t" + rs.getString("Name") + "\t" + rs.getString("Notes") + "\n"); } // end while } catch (Exception e){ System.out.println(e.getMessage()); } // end try } // end constructor private class EventHandler extends WindowAdapter implements ActionListener{ public void windowClosing(WindowEvent e){ Window theWindow = (Window)e.getSource(); theWindow.setVisible(false); theWindow.dispose(); System.exit(0); } // end windowClosing public void actionPerformed(ActionEvent e){ txtOutput.append("\n\n"); try { //generate a query rs = stmt.executeQuery(txtInput.getText()); while (rs.next()){ txtOutput.append(rs.getString("Type") + "\t" + rs.getString("Name") + "\t" + rs.getString("Notes") + "\n"); } // end while } catch (Exception exc){ System.out.println(exc.getMessage()); } // end try } // end action Performed } // end eventHandler } // end class def