select语句检索数据

select语句检索数据

本文介绍了从Java中的mysql select语句检索数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对此有麻烦..我确定我缺少一些简单的东西,但是我只想要Java mysql select语句中的select语句的结果,但我不断得到:

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

这是我的代码:

PreparedStatement 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);

我已经尝试过int fundCode = fundCodeAll.getInt(1);在声明的结尾,但仍然没有运气.如何从select语句中获取结果的int值?

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?

推荐答案

您需要通过ResultSet#next()遍历ResultSet,然后通过任何ResultSet getter获取列值.

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");
    // ...
}

如果结果为零或很多,则可以将它们收集在List中.

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"));
}
// ...

或者如果结果为零或一,则将while替换为if.

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");
}
// ...

另请参见:

  • JDBC教程
  • See also:

    • JDBC tutorial
    • 无关与具体问题无关,请注意 Java命名约定.

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

      这篇关于从Java中的mysql select语句检索数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 21:38