0

我正在创建 Java 程序和 MySQL 数据库之间的连接。代码中唯一未包含的内容是ConnectionValue提取每个特定连接/查询所需的所有相关连接数据的类。这个类确实有效。当我运行代码时,它会创建一个NullPointerException.

import javax.sql.rowset.CachedRowSet;
import java.sql.*;

public class SQLCommands {
    private Connection connection;
    private PreparedStatement preparedStatement;
    private CachedRowSet cachedRowSet;

    public void createConnection(ConnectionValues connectionValues) throws SQLException {
        connection=DriverManager.getConnection(connectionValues.urlString,connectionValues.userName,connectionValues.password);
    }

    public void createCachedRowSet(ConnectionValues connectionValues, String query) throws SQLException {
        cachedRowSet.setUsername(connectionValues.userName);
        cachedRowSet.setPassword(connectionValues.password);
        cachedRowSet.setUrl(connectionValues.urlString);
        cachedRowSet.setCommand(query);
    }

    public void createPreparedStatement(CachedRowSet cachedRowSet) throws SQLException {
        preparedStatement=connection.prepareStatement(cachedRowSet.getCommand());
    }

    public CachedRowSet readDataBase(int dbID, String query) throws Exception {
        ConnectionValues connectionValues=new ConnectionValues(dbID);
        createConnection(connectionValues);
        System.out.println(connectionValues.urlString+"\n"+connectionValues.password+"\n"+connectionValues.userName);
        createCachedRowSet(connectionValues,query);
        createPreparedStatement(cachedRowSet);

        try {
            preparedStatement.execute();
            return cachedRowSet;
        }catch (Exception e){
            System.err.print("ERROR!\nFunction: readDataBase\nClass: SQLCommands\n");
            System.err.print(e);
        }finally {
            connection.close();
        }
        return cachedRowSet;
    }
}

堆栈跟踪报告错误发生在第 14 行。这是cachedRowSet.setUsername(connectionValues.userName);函数中的createCachedRowSet。数据是正确的,我有一个测试打印方法,可以打印代码中的相关信息,它不仅可以无误地提取相同的数据,而且可以打印正确的信息。所以我不确定出了什么问题。认识我,这可能很明显,但我看不到。

4

1 回答 1

1

@TeaDrinker ...请初始化您在第 7 行中定义但未在第 14 行初始化的 cachedRowSet 对象,当您设置其抛出 NullPointerException 的 cachedRowSet 属性时。

于 2020-10-11T19:56:39.833 回答