我正在尝试从 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/