您的位置:首页 > 编程语言 > Java开发

Java获取数据库自增主键表中插入数据的ID

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

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

1.

直接上代码吧:

[java] view
plaincopy





/** 

 * 自增主键主键插入值后获取自增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();  

        }  

    }  

}  

2.如果你想提前知道这条数据插入的ID,你可以
在数据库中专门建立一张表存储各个表的最后一条数据的ID,直接使用存储过程(call test_getNextID)获取Id.

转自:http://blog.csdn.net/zhuyucheng123/article/details/17502007
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: