【问题标题】:Trouble retrieving data with JDBC in Eclipse IDE在 Eclipse IDE 中使用 JDBC 检索数据时遇到问题
【发布时间】:2015-03-17 20:21:30
【问题描述】:

我对 Java 还是很陌生,所以我正在做一个项目来发展我的数据库和 Java 知识。

我已经知道如何将查询添加到数据库中,但现在我在尝试打印它们时遇到了错误。

假设我已经导入了所有必要的东西,例如扫描仪和 sql 语句

这是我的连接类,名为 MainClass:

public static Connection getConnection() throws Exception {
    String driver = "com.mysql.jdbc.Driver";
    String url = "jdbc:mysql://localhost:3306/testTable";
    String username = "placeholder";
    String password = "placeholder";
    Class.forName(driver);
    Connection conn = Driver Manager.getConnection(url, username, password);
    return conn;
}

如果用户键入 !lookup 和一个单词,现在在不同的类中,我希望从名称为字典且列为单词的表中检索该单词的定义,定义:

String userSearch = user_input.next();
String[] userSearchSplit = userSearch.split(" ", 3);

if (userSearchSplit[0].equals("!lookup")) {

    try {
        conn = MainClass.getConnection();
        String query = "select definition from dictionary where word=" + userSearchSplit[1];
        ResultSet result = pstmt.executeQuery(query);

        while (result.next()) {

            String definition = result.getString("definition");
            System.out.println(definition);

        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            pstmt.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

最后,当我尝试查找我在运行前放入表中的单词时,我得到:

java.lang.NullPointerException

【问题讨论】:

  • 你在哪里创建了PreparedStatement的对象?
  • 您的代码中还有很多其他错误!尝试尽快调试
  • 我的实际代码没有任何错误。这是一个必须修改一些东西的娱乐,但这是我最麻烦的部分。您看到的任何错误很可能是我在问题中输入时出现的错误。
  • 只看到上面的代码sn-p我怀疑你还没有初始化pstmt引用变量!这很可能导致Null Pointer Exception
  • 复制粘贴你的代码——使用敏感部分的系统属性——并在你的异常中包含一个完整的堆栈跟踪,好吗?

标签: java eclipse jdbc


【解决方案1】:

检查您的 user_input 是否为空?

我假设你的代码:

ResultSet result = pstmt.executeQuery(query);

作为

Statement pstmt = conn.createStatement();
ResultSet result = pstmt.executeQuery(query);

也可能是你没有正确初始化 pstmt

【讨论】:

  • 我已将我的语句切换到此 PreparedStatement pstmt = conn.prepareStatement("SELECT output FROM commands WHERE name=" + splitMessage[1]); ResultSet 结果 = pstmt.executeQuery();但是现在我在 finally try 块中得到一个空指针异常,它说 pstmt.close();
  • 请为请求粘贴您的代码块。 @Mr.Smithyyy
猜你喜欢
  • 1970-01-01
  • 2019-12-24
  • 1970-01-01
  • 2017-01-19
  • 1970-01-01
  • 2022-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多