【问题标题】:SQL colum not found while in database?在数据库中找不到 SQL 列?
【发布时间】:2018-06-25 10:35:18
【问题描述】:

今天我遇到了一个非常奇怪的错误。

我的错误:

未找到列“naam”。

这是我的查询:

 ResultSet rs1 = con.createStatement().executeQuery("SELECT titel from leningen where naam='" + username + "'");

在这里你可以看到数据库有表:

为什么它告诉我找不到“Naam”?它应该在我的表格视图中显示“你好”,但正因为如此,我得到了

java.lang.NullPointerException

这是我的完整代码,作为敬意:

public void showboeken() throws IOException, SQLException {
    FXMLLoader fxmlLoader = new FXMLLoader();
    fxmlLoader.setLocation(getClass().getResource("showboeken.fxml"));
    Scene scene = new Scene(fxmlLoader.load(), 600, 400);
    Stage stage = new Stage();
    stage.setTitle("New Window");
    stage.setScene(scene);
    stage.show();
    FileReader fr = new FileReader("C:\\Users\\thomasmoed\\IdeaProjects\\bibliotheek\\save.txt");
    BufferedReader br = new BufferedReader(fr);
    String username = br.readLine();
    System.out.println(username);

    try {
        System.out.println("Loading");
        columBoek.setCellValueFactory(new PropertyValueFactory<>("naam"));
    } catch (Exception lol) {
        System.out.println(lol);
    }

    try {
        Class.forName("com.mysql.cj.jdbc.Driver");
        conn = DriverManager.getConnection("jdbc:mysql://localhost/bibliotheek?user=root");
        Connection con = conn;

        ResultSet rs1 = con.createStatement().executeQuery("SELECT titel from leningen where naam='" + username + "'");

        ObservableList<UserModel> data = FXCollections.observableArrayList();

        while (rs1.next()) {
            UserModel usr = new UserModel();
            usr.setNaam(rs1.getString("naam"));
            data.add(usr);
        }

        tableBoekenlening.setItems(data);
        UserModel item = tableBoekenlening.getSelectionModel().getSelectedItem();
        System.out.println(item.getNaam());
    }
    catch (SQLException sqlf) {
        System.out.println(sqlf.getMessage());
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }


}

【问题讨论】:

  • @DawoodibnKareem 我看到了你的回答并给了你 +1 :)
  • 假设一些重要信息在异常消息中
  • 串联不仅暴露给黑客,还会给程序员带来麻烦

标签: java mysql sql jdbc


【解决方案1】:

为了能够运行rs1.getString("naam"),您需要在您选择的列中包含naam。目前,您只是选择titel。所以你的 SQL 语句应该是

"SELECT naam, titel FROM leningen WHERE naam='" + username + "'"

另外,请注意,像这样通过连接构造 SQL 语句会使您容易受到 SQL 注入攻击。我强烈建议学习如何使用准备好的语句而不是使用这种方法。

【讨论】:

  • 为什么我的查询在 PHPmyadmin 中有效,而在 Java 中无效?您的查询有效,谢谢
  • 查询确实按照你第一次给它的形式工作,并返回一堆titel数据。问题是您试图从没有名为 naam 的列的查询中检索名为 naam 的列。
  • @Javaprogrammern00b 我相信不是同一个查询
猜你喜欢
  • 2018-08-20
  • 1970-01-01
  • 1970-01-01
  • 2017-05-21
  • 1970-01-01
  • 2017-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多