我們向數據庫中插入數據的時候,如果有一個字段的類型是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();