数据库连接配置及增删改查(入门)

第一步:创建dao工具类

public class DBConnect {
	private static final String className=  "oracle.jdbc.driver.OracleDriver";
	private static final String url = "jdbc:oracle:thin:@localhost:1521:orcl";
	private static final String user = "humm";
	private static final String password = "tiger";
	private Connection conn=null;
	
	//数据库连接(构造方法)
	public DBConnect(){
		try {
			Class.forName(className);
			this.conn = DriverManager.getConnection(url,user,password);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public Connection getConnection(){
		return conn;
	}
	
	//关闭
	public void close(){
		if(conn!=null){
			try {
			    conn.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		}
		
	}
}
第二步:增删改查--实现层

	public String addEmp() throws Exception{
		HttpServletRequest request = ServletActionContext.getRequest();//这样已经被摈弃了,一般是在action层直接@setter属性值,对象则@setter@getter
		String name = request.getParameter("name");
		int age = Integer.parseInt(request.getParameter("age"));
		String birthday = request.getParameter("birthday");
		resMap = searchEmpInfoService.addEmp(name,age,birthday);
		return SUCCESS;
	}
	@Override  //增加员工
	public Map<String, Object> addEmp(String name, int age, String birthday) throws Exception  {
		Map<String, Object> map = new HashMap<String, Object>();
		DBConnect db = new DBConnect();
		Connection conn = db.getConnection();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		java.util.Date d = sdf.parse(birthday);
		String addEmpSq ="insert into EMP(id,NAME,age,Birthday)values(EMPID_SEQ.Nextval,?,?,?)";
		PreparedStatement pstmt = conn.prepareStatement(addEmpSq);
		pstmt.setString(1, name);
		pstmt.setInt(2, age);
		pstmt.setDate(3, new java.sql.Date(d.getTime()));
		int len =pstmt.executeUpdate();
		map.put("updateLen", len);
		pstmt.close();
		db.close();
		return map;
	}
//查的实现层方法
	PreparedStatement pstmt2 = conn.prepareStatement(sqlcountParam.toString());
				if(id!=""&&id!=null){
					int empId = Integer.parseInt(id);
					++number2;
					pstmt2.setInt(number2, empId);
				}
				if(name!=""&&name!=null){
					++number2;
					pstmt2.setString(number2, name);
				}
				if(birthday!=""&&birthday!=null){
					++number2;
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					java.util.Date date = sdf.parse(birthday);
					Date d = new Date(date.getTime());
					pstmt2.setDate(number2, d);
				}			
				number2=0;
			ResultSet rs2 = pstmt2.executeQuery();//2222222
			int count = 0;
			while(rs2.next()){
				count = rs2.getInt(1);
			}
			map.put("total", count);


 

		



 
  







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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值