java - 使用 Java/Spring 的 MySql 的结果集是空的,它不应该是

标签 java mysql spring

我正在构建代码以使用 Spring 和 Java 从我的标准数据对象访问数据库。为简单起见,我的本地设置使用 MySQL 安装。我已经能够使用我的代码很好地执行插入,但是我无法从选择操作中获取数据...

我在 MySql 中有一张表。数据库名为 jonathan,表名为 Project,其中有一个 id 列。

原来是一行,现在我在表格里插入了三行,都是用我的java/spring-code插入的。

我已经挑出我的问题并在这里浓缩了对特定问题的测试,我删除了所有 where-clause 以确保不涉及参数映射问题。我已经调试了代码以确保我确实收到了数据源。

public class TestDb extends MappingSqlQuery {
    public TestDb() {
        super(StorageFactory.getDataSource(), "Select id from jonathan.Project");
    }
    @Override
    protected Object mapRow(ResultSet arg0, int arg1) throws SQLException {
        System.out.println(arg1+" rows");
        for(int i=0;i<arg1;i++) {
            System.out.println(i+": "+arg0.getString(i));
        }
        return null;
    }
}

当我测试这个时

public static void main(String[] args) {
    TestDb t = new TestDb();
    t.execute();
    System.out.println("Test done");
}

我明白了

0 rows
Test done

我也在表名上尝试了不同的大小写。


解决方法: 我确认我可以只使用 jdbc 选择数据,所以问题是我如何访问结果。

我发现以下方法有效:

public class TestDb extends MappingSqlQuery {
    public TestDb() {
        super(StorageFactory.getDataSource(), "Select id from jonathan.project");
    }
    @Override
    protected Object mapRow(ResultSet arg0, int arg1) throws SQLException {
        System.out.println(arg1 + " rows?");
        boolean b=arg0.first();
        while (b) {
            System.out.println(arg0.getInt(1));
            b=arg0.next();
        }
        return null;
    }
}

打印品说 0 行?

100000
100001
100002
Test done

我仍然想知道 arg1 应该给我什么,因为据我所知它总是说 0。我希望它保存选定的行数。 此外,ResultSet 的文档说

A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on.

给我的想法是我可以通过整个 ResultSet 执行 next(),但如果我执行 first() 然后执行 next(),它似乎工作得很好。

最佳答案

编辑:

你能不能在 mapRow 的开头试试:

if (!this.isCompiled()) System.out.println("Compilation needed !");

那么也请在 mapRow 的开头尝试:

if (!arg0.first()) System.out.println("Empty RS !");
else System.out.println("RS contains lines!");

如果您有“RS 包含行”文本,则执行 i<=arg1而不是 i<arg1在你的循环中。 在其他地方,我会尝试找到其他可以帮助您的东西:)

关于java - 使用 Java/Spring 的 MySql 的结果集是空的,它不应该是,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4425026/

相关文章:

java - 设置 Cron 触发器一次

java - 为什么在 Graphics 对象上调用 dispose() 会导致 JPanel 不呈现任何组件

用于记录 PPC AD 日常性能的 MySQL DB 架构

php - 如何使用 Yii 框架命令 DAO 对象联合所有命令

java - 创建n个任务并在Spring Batch中并行执行它们

java - 在 Wildfly 10 上使用 ActiveMQ Artemis 的 Websockets/STOMP 无法正常工作

java - 从句子中提取短语的算法

mysql - RoR : Cannot change_column in postgres, 在 MySQL 中正常(MySQL 用于开发,Postgres on Heroku)

java - Spring Framework 中的 NullPointerException(或什么?)

java - 跟踪 Spring Web 应用程序上的用户 Activity