存儲過程的寫法:
mysql>create procedure test(
->in username varchar(50),
->in password varchar(50),
->out userid int)
->begin
->set @sql=concat("insert into user(`username`,`password`) values(' ",username,"' ,' ",password,"' )");
->prepare stmt from @sql;
->execute stmt;
->select @@identity into userid;
->end ||
調用:
mysql>call test('name','pwd',@id);
mysql>select @id;
其中的prepare和execute使用請參考手冊
我們在寫數據庫程序的時候,經常會需要獲取某個表中的最大序號數,
一般情況下獲取剛插入的數據的id,使用select max(id) from table 是可以的。
但在多線程情況下,就不行了。
下面介紹三種方法
(1)getGeneratedKeys()方法:
程序片斷:
Connection conn = ;
Serializable ret = null;
PreparedStatement state = .;
ResultSet rs=null;
try {
state.executeUpdate();
rs = state.getGeneratedKeys();
if (rs.next()) {
ret = (Serializable) rs.getObject(1);
}
} catch (SQLException e) {
}
return ret;
(2)LAST_INSERT_ID:
LAST_INSERT_ID 是與table無關的,如果向表a插入數據後,再向表b插入數據,LAST_INSERT_ID會改變。
在多用戶交替插入數據的情況下max(id)顯然不能用。
這就該使用LAST_INSERT_ID了,因爲LAST_INSERT_ID是基於Connection的,只要每個線程都使用獨立的
Connection對象,LAST_INSERT_ID函數將返回該Connection對AUTO_INCREMENT列最新的insert or
update*作生成的第一個record的ID。這個值不能被其它客戶端(Connection)影響,保證了你能夠找回自己的 ID
而不用擔心其它客戶端的活動,而且不需要加鎖。使用單INSERT語句插入多條記錄, LAST_INSERT_ID返回一個列表。
(3)select @@IDENTITY:
String sql="select @@IDENTITY";
@@identity是表示的是最近一次向具有identity屬性(即自增列)的表插入數據時對應的自增列的值,是系統定義的全局變量。一般系統定義的
全局變量都是以@@開頭,用戶自定義變量以@開頭。比如有個表A,它的自增列是id,當向A表插入一行數據後,如果插入數據後自增列的值自動增加至
101,則通過select @@identity得到的值就是101。使用@@identity的前提是在進行insert操作後,執行select
@@identity的時候連接沒有關閉,否則得到的將是NULL值。