【问题标题】:Java sql ResultSet has no dataJava sql ResultSet 没有数据
【发布时间】:2012-09-21 20:21:57
【问题描述】:

我想在 java 中从我的 sql 数据库中提取一个唯一的数据。我尝试使用结果集,但是当我想将第一行提取到一个 int 变量中时,它说结果集没有内容。

这是我的代码

try {

            statement = connexion.createStatement();
            statementArtist = connexion.createStatement();
            String artist = "Mac Miller";
            ResultSet resultat = statement.executeQuery("USE albums SELECT Album.numero_artist FROM Album INNER JOIN Artist ON Album.num_artist = Artiste.num_artist where name like '"+artist+"'");    
            int result = resultat.getInt(1); // Here is the problem
            String query = "USE albums INSERT INTO dbo.Album(Album.num_artist, title, price, genre, date, home, image) VALUES("
                    + result
                    + ", '"
                    + title
                    + "', "
                    + price
                    + ", '"
                    + genre
                    + "', '"
                    + date
                    + "', '"
                    + home
                    + "', '"
                    + image
                    + "')";
            statement.executeUpdate(query);

【问题讨论】:

    标签: java sql-server odbc resultset


    【解决方案1】:

    您应该在结果集上调用next() 方法来“移动”迭代器:

    ...
    ResultSet resultat = statement.executeQuery("USE albums SELECT Album.numero_artist FROM Album INNER JOIN Artist ON Album.num_artist = Artiste.num_artist where name like '"+artist+"'");    
    resultat.next();           
    int result = resultat.getInt(1); // Here is the problem
    ...
    

    如果安全性和更好的性能对您的应用程序很重要,您还应该考虑使用准备好的语句。

    【讨论】:

      【解决方案2】:

      需要使用next(),也要测试结果即

      ResultSet resultat = statement.executeQuery("USE albums SELECT Album.numero_artist FROM Album INNER JOIN Artist ON Album.num_artist = Artiste.num_artist where name like '"+artist+"'");    
      if (resultat.next()) {
          int result = resultat.getInt(1); // Here is the problem
      

      类似 '"+artist+"'" 也容易出错,例如如果艺术家包含引号“'” 大多数数据库都会出现 Sql 错误。不支持使用Sql参数

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-09-06
        • 1970-01-01
        • 2017-08-05
        • 2013-11-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多