zoukankan      html  css  js  c++  java
  • 解决getJdbcTemplate往oracle数据库中插入数据返回主键出错问题

         我们使用Spring中的JdbcDaoSupport往Mysql中插入数据并返回主键代码,我们使用的mysql数据库,主键在数据库中设置为自增长:该类继承自JdbcDaoSupport,所以能直接使用getJdbcTemplate()

    	public int saveUser(String userName,int age,String password){
    		getJdbcTemplate().update(new PreparedStatementCreator() {
    		public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
    			String sql = "insert into tb_user (username,age,password) " +
    			"values(?,?,?)";
    			PreparedStatement ps = connection.prepareStatement(sql,	Statement.RETURN_GENERATED_KEYS);
    			ps.setString(1, userName);
    			ps.setString(2, age);
    			ps.setString(3, password);
    			return ps;
    		}
    	}, keyHolder);
    	Integer generatedId = keyHolder.getKey().intValue();
    	return generatedId;
    	}

    当我们数据库换成oracle数据库时,因为oracle数据库採用序列进行ID标识,我们改动对应的sql语句,其它不变:

    	String sql = "insert into tb_user (id,username,age,password) values(SEQ_ZB_USER.nextval,?,?,?)";

    执行后它会抛出异常:oracle数据库的number类型不能转换为int类型

    换成其它类型也不行,这是由于JdbcDaoSupport中的getJdbcTemplate()不正确oracle支持;

    解决方法:继承Spring中的SimpleJdbcDaoSupport,JdbcDaoSupport能做的,SimpleJdbcDaoSupport基本也能完毕,所以继承后,使用其getSimpleJdbcTemplate()方法;

    	public int saveUser(String userName,int age,String password){
    		//设置參数集合,匹配sql语句中的參数
    		MapSqlParameterSource params=new MapSqlParameterSource();
    		params.addValue("userName", userName);
    		params.addValue("age", age);
    		params.addValue("password", password);
    		
    		KeyHolder keyHolder = new GeneratedKeyHolder();
    		String sql = "insert into zb_user (id,username,age,password) " +
    		"values(SEQ_ZB_JC_PLAN.nextval,:userName,:age,:password)";
    		//须要最后一个String集合列表參数,id表示表主键,否则也会出问题
    		getSimpleJdbcTemplate().getNamedParameterJdbcOperations().update(sql, params, keyHolder, new String[]{"id"});
    		Integer generatedId = keyHolder.getKey().intValue();
    		return generatedId;
    	}

    执行后,成功执行并返回主键;

    至于JdbcDaoSupport和SimpleJdbcDaoSupport的差别,大家能够在网上查阅相关文档进行了解!

  • 相关阅读:
    debian 降级
    linux 常用查看设备命令
    viewstate
    linux图形界面编程基本知识
    Java 不适合编写桌面应用
    temp
    ASP.NET中26个常用性能优化方法
    三层架构与MVC的关系
    分页查询前台HTML+后台asp.net代码
    windows身份验证登入数据库 iis 无法访问数据库
  • 原文地址:https://www.cnblogs.com/yxwkf/p/3902613.html
Copyright © 2011-2022 走看看