續struts學習筆記—Action執行個體:儲存使用者資訊到資料庫(1),這篇文章介紹personDAO代碼,也就是儲存我們使用者資訊的方法。
public class PersonDAO {public void addPerson(Connection conn, Person person) throws SQLException{// TODO Auto-generated method stubString personSQL="insert into tb_person"+"(account,name,birthday,secret,create_date)" +"values (?,?,?,?,?)";String hobbySQL="insert into tb_hobby"+"(person_id,hobby) values (?,?)";PreparedStatement preStmt=null;ResultSet rs=null;try{conn.setAutoCommit(false);preStmt=conn.prepareStatement(personSQL);int index=1;preStmt.setString(index++, person.getAccount());preStmt.setString(index++, person.getName());preStmt.setDate(index++, person.getBirthday());preStmt.setBoolean(index++, person.isSecret());preStmt.setTimestamp(index++, person.getCreateDate());preStmt.executeUpdate();rs=preStmt.getGeneratedKeys();//擷取自動插入的id值rs.next();int personId=rs.getInt(1);preStmt=conn.prepareStatement(hobbySQL);//對Person類裡的List對象hobby進行遍曆for(Iterator<String> iterator=person.getHobby().iterator();iterator.hasNext();){preStmt.setInt(1,personId);preStmt.setString(2, iterator.next());preStmt.addBatch();}preStmt.executeBatch();conn.commit();}finally{if (rs != null)rs.close();if (preStmt != null)preStmt.close();if (conn != null)conn.close();}}}
其中,java.sql.Statement.getGenerateKeys()方法作用是擷取Statement對象執行後產生的索引值value,如果沒有產生,則返回空的ResultSet對象。
另外,用到了iterator介面遍曆集合元素,這裡我詳細介紹下iterator介面:
Iterator介面定義了三個方法:
1.boolean hasNext():如果被迭代的集合元素還沒有被遍曆,返回true。
2.Object next():返回集合裡的下一個元素。
3.void remove():刪除集合裡上一個next方法返回的元素。
上面就是對Person類裡的List對象hobby進行遍曆。