質問

this is the first time I connect to a database with java. I usually use PHP. I need a help to create an array of objects from the result of a query. Let me explain with the code.

class Studente.java

public class Studente {

    String id;
    String username;
    String password;
    String nome;
    String cognome;

    public Studente(String id, String username, String password, String nome, String cognome) {
       this.id = id;
       this.username = username;
       this.password = password;
       this.nome = nome;
       this.cognome = cognome;
    }

    public Studente load(String[] data) {
        Studente studente = new Studente(data[0], data[1], data[2], data[3], data[4]);
        return studente;
    }     
} 

Class StudenteRepository.java:

public class StudenteRepository {

 public Studente[] selectAll() throws SQLException {
    Studente[] studenti = null;
    DBManager db = new DBManager();
    Connection conn = db.connect();
    String query = "SELECT * FROM Studente";
    Statement stmt = conn.createStatement(); 
    ResultSet rs = stmt.executeQuery(query);
    while(rs.next()) {
       //???
    }
    return studenti;
 }

Usually in php I did it this way:

public function selectAll(){
    $db = Database::getInstance();
    $stmt = $db->prepare("SELECT * FROM `users`");
    $stmt->execute();
    $users = array();
    while($result = $stmt->fetch()) {
        $users[] = User::load($result);
    }   
    return $users;
}

How can I change the php code $users[] = User::load($result); in java? Thanks

役に立ちましたか?

解決

What you want is possible in Java:

List<Student> res = new LinkedList<Student>();
while(rs.next()){
   res.add(new Student(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5)));
}

I used a list, because lists ar easier to use. I choose a LinkedList, because they have a better performance while adding elements.

他のヒント

I'm on my phone at the moment so excuse the bad formating

Inside of your while loop create a new user object for each result in the result set

User res = new User(res.getInt("student_id"), res.getString("student_forename"));

ArrayList users = new ArrayList (); users.add(res);

Hope this is enough to get you started, res.getString("student_forename") gets the current value from the student forename column in your db.

Here's a Studente factory:

public Studente createStudente(ResultSet rs) {
  String id = rs.getString(COLUMN_NAME_ID);
  String username = rs.getString(COLUMN_NAME_USERNAME);
  String password = rs.getString(COLUMN_NAME_PASSWORD);
  String nome = rs.getString(COLUMN_NAME_NOME);
  String cognome = rs.getString(COLUMN_NAME_COGNOME);

  return new Studente(id, username, password, nome, cognome);
}

Id suggest changing you quesry to the following so that there's no ambiguity in the column names and order.

SELECT ID, USERNAME, PASSWORD, NOME, COGNOME FROM 'users';

Instead of using Studente load method ,you should use getter and setters for Studente class for best practising. Also you should create a java collection eg. List is suitable for this situation.

List<Studente> studentes = new ArrayList<Studente>();
while(rs.next()){
   Studente studente = new Studente(rs.getString("id"),rs.getString("username"),rs.getString("password"),rs.getString("nome"),rs.getString("cognome"));
   studentes.add(studente);
}

Please dont fire the query Select * from any on the table in the Database. I have attached sample soultion for the same. you can refer it

 List<City> listCities = new ArrayList<City>();
            String sqlString = "select City_Name,Airport from AR_Cities";
            PreparedStatement st = null;
            ResultSet rs = null;

            try
            {
                st = DBConnection.GetConnection().prepareStatement(sqlString);

                rs= st.executeQuery();
                while (rs.next())
                {
                    listCities.add(new City(rs.getString("City_Name"),rs.getString("Airport")));

// in your caase you can use.rs.getString(1) etc.. }

                rs.close();
                DBConnection.CloseConnection(st.getConnection());

            }catch(Exception exp)
            {
                System.out.println("In FlightsADO->GetAllCities  "+ exp.getMessage());
                return null;
            }

            return listCities;
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top