有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java选择*在H2数据库中的位置

我试图在我的程序中与我的嵌入式H2数据库建立JDBC连接。问题是我无法执行带有“WHERE ID=”的简单查询。在我的数据库中,ID是字符串而不是整数(在我的示例中为“D58BE”)

这是我的代码:

   public Milestone findbyId(String id) throws ClassNotFoundException, SQLException {

    Class.forName("org.h2.Driver");
    Connection connection = DriverManager.getConnection("jdbc:h2:~/dao_db", "sa", "");
    PreparedStatement prepareStatement = connection.prepareStatement("SELECT * FROM MILESTONE WHERE ID= 'D58BE'");

问题是相同的查询(“SELECT*FROM MILESTONE,其中ID='D58BE'”)在我的嵌入式数据库中工作得很好(我使用提供用于管理数据库的h2.jar来验证结果)。在eclipse中,我有一个例外:

Exception in thread "main" org.h2.jdbc.JdbcSQLException: Column "D58BE" not found [42122-191]

我尝试了很多东西,但仍然不起作用


共 (1) 个答案

  1. # 1 楼答案

    要直接执行,请创建一条语句并执行SQL:

    Statement statement = connection.createStatement();
    statement.executeQuery("SELECT * FROM MILESTONE WHERE ID= 'D58BE'");
    

    您正在使用准备好的语句,因此需要使用占位符:

    PreparedStatement statement = connection.prepareStatement("SELECT * FROM MILESTONE WHERE ID=?);
    statement.setString(1, "D58BE");
    statement.executeQuery();
    

    编辑

    有关详细示例以及如何处理结果集,请参阅以下教程:https://docs.oracle.com/javase/tutorial/jdbc/basics/processingsqlstatements.html

    就您的情况而言,它应该大致如下:

    ResultSet rs = stmt.executeQuery();
    while (rs.next()) {
        String id = rs.getString("ID");
        String name = rs.getNamex("NAME"); // Assuming there is a column called name.
        System.out.println(id);
    }