java SELECT * WHERE 在 H2 数据库中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36250853/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 01:08:45  来源:igfitidea点击:

SELECT * WHERE in H2 database

javah2

提问by salamanka44

I'm trying to do in my program a JDBC connection with my Embedded H2 database. The problem is that I couldn't execute a simple query with "WHERE ID =". In my databse, the ID are string not integer ('D58BE' in my example).

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

There is my code :

有我的代码:

   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'");

The problem is that the SAME query ("SELECT * FROM MILESTONE WHERE ID= 'D58BE'") works perfectly in my embeded database (I verify the result with the h2.jar provided to manage the database). While in eclipse, I had this exception :

问题是 SAME 查询(“SELECT * FROM MILESTONE WHERE ID = 'D58BE'”)在我的嵌入式数据库中完美运行(我使用为管理数据库提供的 h2.jar 验证结果)。在 eclipse 中,我有这个例外:

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

I tried A LOT of things but it still never works...

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

回答by Willy du Preez

To execute it directly, create a statement and execute your SQL:

要直接执行它,请创建一个语句并执行您的 SQL:

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

You are using a prepared statement, so you need to use placeholders:

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

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

EDIT

编辑

For a detailed example and also how to process a ResultSet, you can look at the following tutorial: https://docs.oracle.com/javase/tutorial/jdbc/basics/processingsqlstatements.html

有关详细示例以及如何处理 ResultSet,您可以查看以下教程:https: //docs.oracle.com/javase/tutorial/jdbc/basics/processingsqlstatements.html

For your case it should be something along the lines of:

对于您的情况,它应该是以下内容:

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);
}