您的位置:首页 > 编程语言 > Java开发

struts学习笔记—Action实例:保存用户信息到数据库(2)

2013-08-10 17:04 323 查看
struts学习笔记—Action实例:保存用户信息到数据库(1),这篇文章介绍personDAO代码,也就是保存我们用户信息的方法。

public class PersonDAO {

	public void addPerson(Connection conn, Person person) throws SQLException{
		// TODO Auto-generated method stub
		String 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进行遍历。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐