gpt4 book ai didi

java - 如何修复 "unreported exception InstantiationException; must be caught or declared to be thrown"

转载 作者:太空宇宙 更新时间:2023-11-03 10:41:58 25 4
gpt4 key购买 nike

<分区>

我正在 NetBeans 8.1 中构建一个简单的 HelloWorld 应用程序。它必须工作简单,一旦编译和运行,它将使用 MySQL 加载数据库帐户中表 acc 的所有数据。

我已将 Connector/J jar 文件包含在我的项目库中并与 MySQL 建立了连接,但 Class.forName(com.mysql.jdbc.Driver).newInstance();一段代码中的行显示“未报告的异常 InstantiationException;必须被捕获或声明为抛出”,我完全不知道该怎么做。我有点被困在这里。

这是我的代码

package learning_jdbc;

import java.sql.*;

public class Hello {
Connection connection;
private void displaySQLErrors(SQLException e) {
System.out.println("SQLException: " + e.getMessage());
System.out.println("SQLState: " + e.getSQLState());
System.out.println("VendorError: " + e.getErrorCode());
}

public Hello() {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (ClassNotFoundException e) {
System.out.println("Class not found.");
}
}

public void connectToDB() {
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/accounts","root","thejoker");
} catch(SQLException e) {
displaySQLErrors(e);
}
}

public void executeSQL() {
try (Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("SELECT * FROM acc")) {
while (rs.next()) {
System.out.println(rs.getString(1));
}
connection.close();
} catch(SQLException e) {
displaySQLErrors(e);
}
}

public static void main(String[] args) {
Hello hello = new Hello();
hello.connectToDB();
hello.executeSQL();
}

}

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com