如何使用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  

它没有唯一的密钥,因为它不会被更改。 我编写了此方法,但出现错误:

  

“您的SQL语法有误;请查看   对应于您的MariaDB服务器版本,以使用正确的语法   'BestellerID,ArtikelNummer,Preis FROM bestellungen WHERE附近的图片   Bestellnummer = 1'在第1行的线程“ main”中的异常   java.lang.IndexOutOfBoundsException:索引1越界长度   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,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;
}}
toddfsy001 回答:如何使用Java从MySQL数据库返回多行

您可以尝试以下方法:

final String SQL ="SELECT BestellerID,ArtikelNummer,Preis 
                  FROM bestellungen WHERE Bestellnummer = ?";
本文链接:https://www.f2er.com/3169852.html

大家都在问