设为首页 加入收藏

TOP

Java获取数据库自增主键表中插入数据的ID
2014-11-24 03:23:38 来源: 作者: 【 】 浏览:0
Tags:Java 获取 数据库 插入 数据

这段代码是为了解决,JDBC中在给自增表插入数据后获取插入数据自动生成的ID问题。上网找了半天资料,原来在JDK中有提供方法哎。

参考资料点击打开链接感谢诸位高手的指点。

直接上代码吧:

	/**
	 * 自增主键主键插入值后获取自增ID
	 * @param sql
	 * @return
	 */
	public int insertIntoDB(String sql){
		Connection conn = null;
		Statement state = null;
		ResultSet rs = null;
		int key = -1;
		try{
			conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jx3", "root", "root");
			state = conn.createStatement();
			state.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
			rs = state.getGeneratedKeys();
			if(rs.next()){
				key = rs.getInt(1);
			}
			return key;
		}catch (SQLException e) {
			e.printStackTrace();
			return key;
		}finally{
			try{
				if(rs != null){
					rs.close();
					rs = null;
				}
				if(state != null){
					state.close();
					state = null;
				}
				if(conn != null){
					conn.close();
					conn = null;
				}
			}catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇saiku查询出错如何debug(saiku查.. 下一篇在R12下加载JavaBean,配置FORMS_..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·MySQL 安装及连接-腾 (2025-12-25 06:20:28)
·MySQL的下载、安装、 (2025-12-25 06:20:26)
·MySQL 中文网:探索 (2025-12-25 06:20:23)
·Shell脚本:Linux Sh (2025-12-25 05:50:11)
·VMware虚拟机安装Lin (2025-12-25 05:50:08)