首页 技术 正文
技术 2022年11月15日
0 收藏 775 点赞 2,464 浏览 1694 个字

在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);
}
}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,966
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,487
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,332
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,115
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,748
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,783