2012-09-30 49 views
0

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

这里是我的代码

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

你应该叫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 
... 

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

+0

哦,非常感谢我的错误!!我忘了.next() – Sebastien

0

需要使用下一个(),也应该测试结果即

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 

也类似“‘+艺术家+’””是容易出错,例如,如果艺术家包含引号“'”你可能会遇到大多数数据库的Sql错误。使用Sql参数的最佳模式