如何使用java从mysql数据库返回多行
I want to select multiple rows and return them in an Arraylist.
我的数据库结构如下所示:
1 Bestellnummer int(20)
2 BestellerID int(20)
3 ArtikelNummer int(20)
4 Anzahl int(10)
5 Preis double
它没有唯一的密钥,因为它不会被更改。 我编写了此方法,但得到了错误:
" You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'BestellerID,ArtikelNummer,Preis FROM bestellungen WHERE Bestellnummer = 1' at line 1Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 1 out-of-bounds for length 0"
public ArrayList<Bestellung> getBestellung (int i) throws SQLException {
ArrayList<Bestellung> Auftrag = new ArrayList<>();
final String SQL ="SELECT* BestellerID,ArtikelNummer,Preis FROM bestellungen WHERE Bestellnummer = ?" ;
ResultSet rs = null ;
try {
PreparedStatement stmt = con.prepareStatement(SQL,ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
stmt.setInt(1, i);
rs = stmt.executeQuery();
System.out.println("test");
while (rs.next()) {
Bestellung test = new Bestellung( i, rs.getInt("BestellerID"), rs.getInt("ArtikelNummer"), rs.getDouble("Preis"));
Auftrag.add(test);
}
}
catch (SQLException e) {
System.err.print(e);
}
finally {
if (rs!=null) {rs.close();
}
}
return Auftrag;
}
}
public class Bestellung {
private int Bestellnummer, BestellerID,ArtikelNummer,Anzahl;
private double Preis;
以下是对象将位于Arraylist中的类:
Bestellung (int Bestellnummerin,int BestellerIDin,int ArtikelNummerin,double Preisin)
{
this.Bestellnummer = Bestellnummerin ;
this.BestellerID = BestellerIDin ;
this.ArtikelNummer = ArtikelNummerin;
this.Anzahl = 1;
this.Preis = Preisin;
}}
# 1 楼答案
您可以尝试以下方法: