2012-09-30 122 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參數的最佳模式