• Java从入门到精通——数据库篇之JAVA中的对Oracle数据库操作


              在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);
    	}
    }  
    



     

    Meet so Meet. C plusplus I-PLUS....
  • 相关阅读:
    vux 使用 loading 组件
    vux 使用 font-awesome
    批处理常用符号详解
    jQuery.parseJSON vs JSON.parse
    MVC view操作(Razor语法)
    原生JavaScript技巧大收集
    .Net实现表达式计算(公式) 表达式字符串
    .Net文档下载
    MVC下载文档
    .Net实现Word文档及导出
  • 原文地址:https://www.cnblogs.com/iplus/p/4490423.html
Copyright © 2020-2023  润新知