开发者

retrieving data from mysql select statement in java

Having trouble with this..I'm sure I'm missing something simple but I simply want the result of a select statement in a java mysql select statement but I keep getting:

com.mysql.jdbc.JDBC4ResultSet@1c190c99

Here's my code:

P开发者_JS百科reparedStatement Findstatement;
                Findstatement = con.prepareStatement("SELECT Code from DataMaster where DataName= (?) ");
                Findstatement.setString(1, Name);  // I have a variable in my file named 'Name' 
                ResultSet CodeAll  = Findstatement.executeQuery();
                System.out.println(CodeAll);

I've tried int fundCode = fundCodeAll.getInt(1); at the end of the statement but still no luck. How do I get the int value of the the result from the select statement?


You need to iterate over the ResultSet by ResultSet#next() and then get the column values by any of the ResultSet getters.

resultSet = statement.executeQuery();
while (resultSet.next()) {
    int code = resultSet.getInt("Code");
    // ...
}

If there are zero or many results, then you can collect them in a List.

List<Integer> codes = new ArrayList<Integer>();
// ...
resultSet = statement.executeQuery();
while (resultSet.next()) {
    codes.add(resultSet.getInt("Code"));
}
// ...

Or if there is zero or one result, then replace while by if.

int code = 0;
// ...
resultSet = statement.executeQuery();
if (resultSet.next()) {
    code = resultSet.getInt("Code");
}
// ...

See also:

  • JDBC tutorial

Unrelated to the concrete problem, please pay attention to the Java naming conventions.


After getting the resultset, you should iterate over it:

while(CodeAll.next()){

    String value = CodeAll.getString("column name");

    //get all values depending on type, like getString for string, 
    //getDouble for double, etc
}

Just get values from result set and do whatever you want from it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜