0

我想从 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);
4

2 回答 2

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
...

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

于 2012-09-30T22:15:52.297 回答
0

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

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 参数不支持

于 2012-09-30T22:26:12.570 回答