所以我声明了一个SQL连接,如下所示:
public class db {
public void run() throws SQLException {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection cn = DriverManager.getConnection("jdbc:mysql://localhost:3306/project", "rizkiaswangga", "");
} catch (SQLException e) {
System.out.println(e.getMessage());
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
我只是想先连接MariaDB到我的Java项目,但是,虽然我已经声明了SQLException,我仍然遇到如下错误消息:
Exception in thread "AWT-EventQueue-0" java.lang.RuntimeException: Uncompilable code - unreported exception java.sql.SQLException; must be caught or declared to be thrown
当我试图从其他类运行时:
public class Start extends javax.swing.JFrame {
/**
* Creates new form Start
*/
public Start() {
initComponents();
db myDb = new db();
myDb.run();
}
我的代码有什么问题?任何帮助都将是感激的:)
在运行方法中,您已经声明了throws SQLException
,但您没有抛出异常。
throws SQLException
。用public void run()
法去除throw SQLException
public class db {
public void run() {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection cn = DriverManager.getConnection("jdbc:mysql://localhost:3306/project", "rizkiaswangga", "");
} catch (SQLException e) {
System.out.println(e.getMessage());
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}