java对oracle数据库操作,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);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值