Java sql ResultSet没有数据

时间:2012-09-30 22:13:56

标签: java sql-server odbc resultset

我想从java中的sql数据库中只提取一个数据。我试图使用resultSet,但是当我想将第一行exctract为int Variables时,它表示resultSet没有内容。

这是我的代码

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

2 个答案:

答案 0 :(得分: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+"'");    
resultat.next();           
int result = resultat.getInt(1); // Here is the problem
...

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

答案 1 :(得分:0)

需要使用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 +”'“也容易出错,例如,如果艺术家包含引号”'“ 你会得到大多数DB的Sql错误。最快使用Sql参数