1 Reply Latest reply: Dec 3, 2009 2:42 PM by 800387 RSS

    connectivity probs

      after writing whole java program and sql querries how to connect the database and gui ???
      my program on windows is :-

      import java.awt.*;
      import java.awt.event.*;
      import java.sql.*;
      import javax.swing.*;

      public class Employee

      public static void main(String args[])
           Frame f=new Frame("New Doctor");
           TextField t1,t2,t3,t4,t5,t6,t7;
           t1=new TextField(15);
           t2=new TextField(15);
           t3=new TextField(15);
           t4=new TextField(15);
           t5=new TextField(15);
           t6=new TextField(15);
           t7=new TextField(15);
           Label Fname = new Label("First Name :");
           Label Lname = new Label("Last Name :");
           Label gender = new Label("Gender");
           Label Date_of_birth = new Label("Date of birth :");
           Label Date_of_join = new Label("Date of join :");
           Label Payment = new Label("Package :");
           Label education = new Label("Education");
           Button b1 = new Button ("Register");

           f.setLayout(new FlowLayout());
           b1.add ActionListener(new A());

      static class A implements ActionListener

           public void actionPerformed(ActionEvent e)
                Connection con=null;
                Statement st=null;
                ResultSet rs=null;
                     String qry="insert into employee values(t1.getText(),t2.getText(),t3.getText(),t4.getText(),t5.getText(),t6.getText(),t7.getText())";
                     int k =st.executeUpdate(qry);
                catch(Exception ex)
        • 1. Re: connectivity probs
          So much to say, I do not know where to begin. First, always format your code using the 'code' button or by adding code tags. No one will bother reading your stuff otherwise.

          Second, it is generally bad practice to put everything in one place like that. Java is OO. Make a few objects, even if they are only helper objects. Primarily, this will mean putting the JDBC code in its own class (and by that I mean outside of something like a listener).

          Third, you must close your JDBC resources in a finally block. http://en.wikipedia.org/wiki/Java_Database_Connectivity. Failure to do so will result in resources leaking and your application (or database) grinding to a halt very quickly.

          Fourth, the URL for the JDBC-ODBC driver is not correct. Java is case-sensitive, and my guess is that the driver URL is as well. http://java.sun.com/j2se/1.3/docs/guide/jdbc/getstart/bridge.doc.html

          Fifth, before you call Frame#setVisible(true), be sure to all Frame#pack() so the components have the proper size and layout.

          Sixth, it is generally best to call Connection#setAutoCommit(false) right after you obtain it. Then use Connection#rollback() on an error or Connection#commit() to finalize your changes.

          - Saish