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 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 do have a getConnection()
method too.
Here is what im using to call the viewValue
method:
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 code above was written for a ButtonHandler
Right now, for the println
I'm getting a "com.mysql.jdbc.JDBC4ResultSet@1e72cae
" .. I don't understand how it is so.. but I'm assuming that ResultSet is the wrong choice here.
My question is.. what can i use there that can work?
Any help or clue as to what im doing wrong is much appreciated.
You need to change
to
Try This:
change it to
and
works !!!
Use
rs.getInt(1)
orrs.getString(1)
to retrieve the actual value from theResultSet
. Then read a JDBC tutorial.Change :
To:
rs.toString returns the result of the
toString
method of the ObjectResultSet
.rs.getString(1)
gives you the first parameter of the resultset as aString
.is because you return the
ResultSet
object here ,value = rs.toString();
From docs,
You should tell the result set to get the value from the column ,
through index
or through column name