我们向数据库中插入数据的时候,如果有一个字段的类型是auto_increment(Mysql中的数据类型,其他数据库类似),我们插入的时候value应该为null,这个大家都知道,但是如果这张表中还有另外一个字段,它的类型不是auto_increment,但他的值必须要等于这条记录的auto_increment字段的值怎么办?具体有如下示例:
Table_Name:Test
Table_Column:id(auto_increment)title(varchar(255))cont(text)rootid(int)
在这张表中,我们插入数据的时候Statement可能是这样的:
insertintoTestvalues(null,'testTitle','testCont',?);
?代表rootid的值,如果我们现在要求rootid必须等于id,那请问rootid的值该怎么确定呢?
SolutionInJava:
先为rootid插入一个常量值:
Stringsql="insertintoTestvalues(null,'testTitle','testCont',-1)";
pstmt=conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
pstmt.executeUpdate();
然后获取
ResultSetrsKey=pstmt.getGeneratedKeys();
rsKey.next();
intkey=rsKey.getInt(1);
sql="updateTestsetrootid="+key+"whereid="+key;
pstmt=conn.prepareStatement(sql);
pstmt.executeUpdate();
reKey.close();
pstmt.close();
conn.close();
转载于:https://blog.51cto.com/gogofun/1269504