Getting one value from SQL select statement in Java

前端 未结 6 893
野性不改
野性不改 2020-12-18 04:27

I\'m trying to return a value from a select statement. Its only one value because the value I\'m returning is from the primary key column.

The SQL statement is

相关标签:
6条回答
  • 2020-12-18 05:03

    You need to change

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

    to

     while (rs.next())
        value = rs.getString("itemNo");
    
    0 讨论(0)
  • 2020-12-18 05:11
    Right now, for the println I'm getting a "com.mysql.jdbc.JDBC4ResultSet@1e72cae"
    

    is because you return the ResultSet object here , value = rs.toString();

    From 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.

    You should tell the result set to get the value from the column ,

    value = rs.getString(1);
    

    through index

    value = rs.getString("itemNo");
    

    or through column name

    0 讨论(0)
  • 2020-12-18 05:11

    change it to

    if(rs.next())
    

    and

    rs.getString("itemNo");
    

    works !!!

    0 讨论(0)
  • 2020-12-18 05:21

    Use rs.getInt(1) or rs.getString(1) to retrieve the actual value from the ResultSet. Then read a JDBC tutorial.

    0 讨论(0)
  • 2020-12-18 05:22

    Change :

    value = rs.toString();
    

    To:

    value = rs.getString(1);
    

    rs.toString returns the result of the toString method of the Object ResultSet. rs.getString(1) gives you the first parameter of the resultset as a String.

    0 讨论(0)
  • 2020-12-18 05:23

    Try 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.getString(1);
        } 
    
        catch (SQLException e ) 
        {
            e.printStackTrace();
        } 
    
        finally
        {
            if (stmt != 
            null) { stmt.close(); }
        }
    
        return value;
    
    }
    
    0 讨论(0)
提交回复
热议问题