java - 从 Java 中的 SQL select 语句中获取一个值

标签 java jdbc resultset sql

我正在尝试从 select 语句返回一个值。它只有一个值,因为我返回的值来自主键列。

SQL语句是SELECT itemNo FROM item WHERE itemName = 'astringvalue';

我获取值的方法如下所示:

private String viewValue(Connection con, String command) throws SQLException 
    {
        String value = null;
        Statement stmt = null;

        try 
        {
            stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery(command);

            while (rs.next())
                value = rs.toString();
        } 

        catch (SQLException e ) 
        {
            e.printStackTrace();
        } 

        finally
        {
            if (stmt != 
            null) { stmt.close(); }
        }

        return value;

    }

我也有一个 getConnection() 方法。

这是我用来调用viewValue方法的方法:

if((action.getSource() == btnSave) ||(action.getSource() == btnSavePrint) )
        {
            String findItemNoCommand = "SELECT itemNo FROM `item` WHERE itemName = '" + itemList.getSelectedItem() + "'";

            try 
            {
                itemNo = viewValue(conn, findItemNoCommand);
            }
            catch (SQLException e) 
            {
                e.printStackTrace();
            }

            System.out.println(itemNo);
        }

上面的代码是为ButtonHandler编写的

现在,对于 println,我得到一个“com.mysql.jdbc.JDBC4ResultSet@1e72cae”..我不明白这是怎么回事.. 但我假设 ResultSet 在这里是错误的选择。

我的问题是..我可以在那里使用什么可以工作?

非常感谢任何关于我做错了什么的帮助或线索。

最佳答案

Right now, for the println I'm getting a "com.mysql.jdbc.JDBC4ResultSet@1e72cae"

是因为你在这里返回了ResultSet对象,value = rs.toString();

来自 docs ,

A ResultSet object is a table of data representing a database result set, which is usually generated by executing a statement that queries the database

You access the data in a ResultSet object through a cursor. Note that this cursor is not a database cursor. This cursor is a pointer that points to one row of data in the ResultSet. Initially, the cursor is positioned before the first row. The method ResultSet.next moves the cursor to the next row. This method returns false if the cursor is positioned after the last row. This method repeatedly calls the ResultSet.next method with a while loop to iterate through all the data in the ResultSet.

你应该告诉结果集从列中获取值,

value = rs.getString(1);

通过索引

value = rs.getString("itemNo");

或通过列名

关于java - 从 Java 中的 SQL select 语句中获取一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26711383/

相关文章:

java - 将时间字符串转换为长值?

java - 如何使用 ObjectOutputStream 保存对象列表以及如何读取它们?

java - 在 TreeTableView 中选择子项时还要选择父项直至根

java - H2:getArray 仅返回一个元素

java - 无法连接到 Tomcat 应用程序中的 Derby 数据库

java - 如何正确覆盖 Spring 和 Hibernate 的 BasicDataSource

java - 如何从jdbc中带参数的存储过程中获取结果集

java - 如何从 ResultSet 获取要更新的 JTable 数据

java - 为什么在 FXML 中添加两个 ColumnConstraint?

java - JDBC ResultSet 总行数