未报告的异常ClassNotFoundException;必须是catch或thrown class.forName(sun.jdbc.odbc.JdbcOdbcDriver)

时间:2014-10-06 05:28:46

标签: java

 import   java.sql.*; 
import   java.awt.*; 
import   java.awt.event.*;
import   javax.swing.*;
 class DeleteDemo extends Frame implements
     ActionListener {
                        Label l1;
                       Button b1;
                       TextField t1;
                       DeleteDemo()
                        {   
                         setVisible(true);
                         setSize(400,400);
                         l1=new  Label("Enter Id");
                         b1=new Button("Delete");
                         t1=new TextField(20);
                         setLayout(new FlowLayout());
                         add(l1);add(t1);
                         add(b1);
                         b1.addActionListener(this);
                        } 


         public void actionPerformed(ActionEvent  e)
         {
                           if(e.getSource()==b1)
                          {      
                              try
                              {         
                                      System.out.println("Data try to delete");
                                      String id=t1.getText(); 
                                      l1.setText("hi");
                                      Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                        Connection con=DriverManager.getConnection("Jdbc:Odbc:xyz","","");
                Statement st=con.createStatement();
                st.executeUpdate("delete from tblEmp where id ='"+id+"' ");
                System.out.println("Data has been deleted");
            }catch(SQLException eb){} 
         }
     }     
        public static void main(String args[ ])       {
            DeleteDemo dtl=new DeleteDemo();        } 
      }

1 个答案:

答案 0 :(得分:1)

Class.forName(String)如果无法加载已传递给其名称的类,则会引发ClassNotFoundException(例如,如果您在类路径中遗漏了一个jar)。这是一个经过检查的例外情况,必须向上抛出(例如,将throws ClassNotFoundException添加到您的方法声明中),或者抓住:

try {
    System.out.println("Data try to delete");
    String id=t1.getText(); 
    l1.setText("hi");
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection con=DriverManager.getConnection("Jdbc:Odbc:xyz","","");
    Statement st=con.createStatement();
    st.executeUpdate("delete from tblEmp where id ='"+id+"' ");
    System.out.println("Data has been deleted");
} catch(ClassNotFoundException cne) {
    System.err.println("Could not load JDBC driver");
} catch(SQLException eb) {
    System.err.println("Could not delete data");
}