Getting a single value from a SQL select statement in Java

I am trying to return a value from a select statement. Its only value, because the value I return comes from the primary key column.

SQL statement SELECT itemNo FROM item WHERE itemName = 'astringvalue';

My method for getting the value looks like this:

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;

    }

I also have a method getConnection().

Here is what I used to call the method 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);
        }

The above code was written for ButtonHandler

Right now, for printlnI get " com.mysql.jdbc.JDBC4ResultSet@1e72cae". I do not understand how this happens. But I guess ResultSet is the wrong choice here.

My question is: what can I use there, which can work?

Any help or hint regarding what I am doing wrong is greatly appreciated.

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

, ResultSet , value = rs.toString();

docs,

ResultSet , set, ,

ResultSet . , . , ResultSet. . ResultSet.next . false, . ResultSet.next while ResultSet.

, ,

value = rs.getString(1);

value = rs.getString("itemNo");

+5

:

value = rs.toString();

To:

value = rs.getString(1);

rs.toString toString ResultSet. rs.getString(1) String.

+1

rs.getInt(1) rs.getString(1) ResultSet. JDBC.

+1

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

 while (rs.next())
    value = rs.getString("itemNo");
+1

if(rs.next())

rs.getString("itemNo");

!!!

+1

:

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.getString(1);
    } 

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

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

    return value;

}
0

All Articles