struts學習筆記—Action執行個體:儲存使用者資訊到資料庫(2)

來源:互聯網
上載者:User

續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進行遍曆。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.