实验环境.
-
create table user_follow_sender(
-
UserID bigint not null comment '粉丝的用户ID',
-
FollowUserID bigint not null comment '关注的用户ID',
-
FollowState smallint default 1 comment '关注状态.1表示有效,0表示取关',
-
CreateTime timestamp not null default current_timestamp comment '创建时间',
-
UpdateTime timestamp not null default current_timestamp on update current_timestamp comment '更新时间',
-
primary key (UserID,FollowUserID)
-
) comment '用户关注粉丝表.发起方';
-
-
delimiter $$
-
create procedure add_follow_sender(
-
pUserID bigint,
-
pFollowUserID bigint,
-
out pRowCount int
-
)
-
begin
-
insert into user_follow_sender(
-
UserID,
-
FollowUserID,
-
FollowState
-
)
-
values(
-
pUserID,
-
pFollowUserID,
-
1
-
)
-
ON DUPLICATE KEY UPDATE
-
FollowState=1
-
;
-
select row_count() into pRowCount;
-
end $$
-
delimiter ;
如果是
Insert,row_count() 为1
Update,row_count() 为2
Update的目标值和原来一样,row_count() 为0
但如果通过 JDBC 调用,最后一种情况也会返回1,这是因为客户端连接时如果设置了 CLIENT_FOUND_ROWS 标志,会用 rows found 代替 rows affected 当做返回值,而JDBC默认是会设置该标志的。在 JDBC 连接字符串中指定 useAffectedRows=true 可以取消这个flag。
作为JDBC调用,不加useAffectedRows参数
url = "jdbc:mysql://127.0.0.1:3306/" + dbName;
-
public void test() throws SQLException {
-
Connection con = getConnection(dbPrefix + 0);
-
con.setAutoCommit(false);
-
-
CallableStatement cs = con.prepareCall("{call add_follow_sender(?,?,?)}");
-
-
cs.setLong(1, 1010001);
-
cs.setLong(2, 1010002);
-
-
cs.registerOutParameter(3, Types.INTEGER);
-
-
cs.execute();
-
-
System.out.println( cs.getInt(3));
-
con.commit();
-
cs.close();
-
con.close();
-
}
Insert,返回值为1
Update的目标值和原来一样,返回值为1
Update的目标值和原来不一样,返回值为2
增加useAffectedRows参数
url = "jdbc:mysql://127.0.0.1:3306/" + dbName+"?useAffectedRows=true";
Insert,返回值为1
Update的目标值和原来一样,返回值为0
Update的目标值和原来不一样,返回值为2
参考:
http://novoland.github.io/%E6%95%B0%E6%8D%AE%E5%BA%93/2015/08/17/INSERT%20ON%20DUPLICATE%20KEY%20UPDATE%20%E5%87%A0%E4%B8%AA%E8%A6%81%E6%B3%A8%E6%84%8F%E7%9A%84%E9%97%AE%E9%A2%98.html
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29254281/viewspace-2121455/
,如需转载,请注明出处,否则将追究法律责任。