我想从java中的sql数据库中提取一个数据。我尝试使用 resultSet,但是当我想将第一行减入 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);
您应该在结果集上调用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
...
如果安全性和更好的性能对您的应用程序很重要,则还应考虑使用预准备语句。
需要使用 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
此外,诸如"+艺术家+"之类的容易出错,例如,如果艺术家包含引号"大多数数据库都会出现 Sql 错误。使用 Sql 参数提供