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

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 viewValuemethod:

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.

解决方案

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值