Java获取数据库自增主键表中插入数据的ID
Jun 07, 2016 pm 03:22 PM
java
primary key
insert
data
database
self-increasing
Obtain
in the table
这段代码是为了解决,JDBC中在给自增表插入数据后获取插入数据自动生成的ID问题。上网找了半天资料,原来在JDK中有提供方法哎。 参考资料点击打开链接感谢诸位高手的指点。 直接上代码吧: /** * 自增主键主键插入值后获取自增ID * @param sql * @return */p
这段代码是为了解决,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(); } } }
Copy after login
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot Article
How Long Does It Take To Beat Split Fiction?
3 weeks ago
By DDD
Repo: How To Revive Teammates
3 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌

Hot tools Tags

Hot Article
How Long Does It Take To Beat Split Fiction?
3 weeks ago
By DDD
Repo: How To Revive Teammates
3 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Break or return from Java 8 stream forEach?
