【问题标题】:Programming in Java Help?! (Netbeans)Java 编程 帮助?! (网豆)
【发布时间】:2015-04-13 09:54:44
【问题描述】:

我是 Java 新手,基本上我的问题是 - 如何将 MS 访问链接到 NetBeans,我已经尝试了所有方法,但似乎没有任何效果。 p>

public Student1 (){


   connect ();
}

public void connect () {

    try{

        String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
        Class.forName(driver);

        String Student1 = "jdbc:odbc:Database1";
        con = DriverManager.getConnection(Student1);
        st = con.createStatement();
        String sql = "select * from Student1";
        rs = st.executeQuery(sql);

        while (rs.next())
        {
            String fname = rs.getString("First Name");
            String lname = rs.getString("Last Name");
            String dob = rs.getString("DOB");
            String studentid = rs.getString("StudentID");
            String mobileno = rs.getString("MobileNo");
            String address = rs.getString("Address");
            String email = rs.getString("Email");


            System.out.println(fname + " "+lname+" "+dob+" "+studentid+" "+mobileno+" "+address+" "+email);

        }

    }catch (Exception ex){

    }

}

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    // TODO code application logic here
new Student1();
}

}

我得到一条黄线:

connect ();
catch (Exception ex)
new Student1();

【问题讨论】:

  • 如果您将鼠标悬停在这一行上,NetBeans 应该会提示您出了什么问题。这是什么提示?
  • 如果您在catch() 中添加一些日志记录,您可能能够诊断出错误。
  • 在你的 catch 块中使用 Exception#printStackTrace() 方法!!它会告诉你原因
  • @Tichodroma 在 connect() 上,提示说:构造函数中的可覆盖方法调用,在 catch (Exception ex) 上说:catch (Java.lang.exception) 太板了,它捕获以下异常类型:Java.lang.clasNotFound Eeption 和 Java.sql.SQLException 和 new Student1() 正在说;新实例,忽略,用介绍包围

标签: java netbeans jdbc


【解决方案1】:

黄线表示the catch java.lang.exception is too broad

Exception 类是 IO 和运行时异常的超类。在那里,您可以使用它的子类或继续使用它。由你决定。

文档Here

connect() 提示是:构造函数中的可覆盖方法调用

这可能会导致麻烦。调用该方法时,对象的状态可能不一致。请参考Here

new Student1(); 出现黄线,因为您创建了一个实例,但没有将其存储在任何地方。

这样可以解决问题。

Student1 n = new Student1();

【讨论】:

    【解决方案2】:

    由于Student1 类的构造函数正在调用同一类中的可覆盖方法connect(),因此导致该错误。

    这是不好的做法的原因是,如果有人继承 Student1 并覆盖 connect(),那么他们也将直接更改 Student1 的父类构造函数的行为。这是封装的突破。

    示例:

    public class NewStudent extends Student1 {
        // constructor, etc...
    
        @Override
        public void connect() {
            // do something new here
            System.out.println("calling NewStudent.connect()");
        }
    }
    
    NewStudent student = new NewStudent();
    

    这将输出calling NewStudent.connect()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-04
      • 1970-01-01
      • 1970-01-01
      • 2011-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-20
      相关资源
      最近更新 更多