现在的位置: 首页 > 综合 > 正文

JAVA中的对Oracle数据库操作

2013年10月28日 ⁄ 综合 ⁄ 共 1722字 ⁄ 字号 评论关闭

          在Java中对Oracle数据库的操作分为两种:一、查询。二、非查询。

    下面是我对其进行总结:

      一、查询数据

  /**	 * 根据用户代码查询
	 * @param userId
	 * @return 如果存在返回User 如果不存在则返回Null
	 */
public User findUserById(String userId){
		      //sql语句
	              String sql="select user_id,user_name,password,contact_tel,email,create_date from t_user where user_id=?";
			//创建Connection对象
			Connection conn=null;
		      //创建PreparedStatement对象
			PreparedStatement pstmt=null;
			//创建ResultSet对象
			ResultSet rs=null;
			User user=null;
					
			try{
			    conn=DbUtil.getConnection();
			    //创建包含带参数占位符的 SQL 语句的 PreparedStatement 对象:
			     pstmt=conn.prepareStatement(sql);
			    //给每一个参数传值
			     pstmt.setString(1, userId);
			    //执行查询语句
			     rs=pstmt.executeQuery();
			    //取出数据
			     if(rs.next()){
				      user=new User();
					user.setUserId(rs.getString("user_id"));
					user.setUserName(rs.getString("user_name"));
					user.setPassword(rs.getString("password"));
					user.setContactTel(rs.getString("contact_tel"));
					user.setEmail(rs.getString("email"));
					user.setCreateDate(rs.getTimestamp("create_date"));
						}
			}catch(SQLException e){
				e.printStackTrace();
			}finally{
				DbUtil.close(rs);
				DbUtil.close(pstmt);
				DbUtil.close(conn);
				}
				return user;
			}

      二、非查询的操作(增、删、改)

public void addUser(User user){
	//SQL语句
	String sql= "insert into t_user (user_id, user_name, password, contact_tel, email, create_date) " +" values (?, ?, ?, ?, ?, ?)";
	//定义数据库连接
	Connection conn=null;
	//定义一个PreparedStatement对象
	PreparedStatement pstmt=null;
	try{
		
		conn=DbUtil.getConnection();
		//创建包含带参数占位符的 SQL 语句的 PreparedStatement 对象:
		pstmt=conn.prepareStatement(sql);
		//给每一个参数传值
		pstmt.setString(1, user.getUserId());
		pstmt.setString(2, user.getUserName());
		pstmt.setString(3,user.getPassword());
		pstmt.setString(4,user.getContactTel());
		pstmt.setString(5,user.getEmail());
		pstmt.setTimestamp(6, new Timestamp(new Date().getTime()));
		//执行语句
		pstmt.executeUpdate();
	}catch(SQLException e){
		e.printStackTrace();
	}finally{
		DbUtil.close(pstmt);
		DbUtil.close(conn);
	}
}  

 

 

抱歉!评论已关闭.