MYSQL存储过程&&JAVA读取结果集

0.场景是:使用登录ID和密码进行登录验证,返回该用户对应的一行数据
1.定义存储过程:
delimiter $$
drop procedure if exists verify $$
/* 两个输入 loginId,登录ID,psw,登录密码 */
create procedure verify (
    in loginId varchar(99),
    in psw varchar(99)
)
begin
    declare tmppsw varchar(99) default "";
    select * from baseuser where baseuser.loginId = loginId;
    if psw = tmppsw 
        then select * from baseuser where baseuser.loginId = loginId;
    end if;
end $$
delimiter ;
2.获取一个存储过程:(返回值是一个CallableStatement类型的对象)
/**
 * call a procedure
 * 
 * @param procedureName
 * @param argsNumber
 *            : number of parameters
 * @return CallableStatement
 */
public CallableStatement getProcedureStmt(String procedureName,
        int argsNumber, Connection con) {
    CallableStatement stmt = null;
    StringBuilder builder = new StringBuilder();
    builder.append("{call " + procedureName + " (");
    for (int i = 0; i < argsNumber; i++) {
        builder.append(i == argsNumber - 1 ? "?)}" : "?,");
    }
    System.out.println(builder.toString());
    try {
        stmt = con.prepareCall(builder.toString());
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return stmt;
}
3.调用这个存储过程
/**
 * login
 * 
 * @param baseUser
 * @return true if login successfully, false otherwise
 */
public boolean mLogin(BaseUser baseUser) {
    boolean isSuccess = false;
    CallableStatement stmt = getProcedureStmt("verify", 2);
    try {
        stmt.setString(1, baseUser.getLoginId());
        stmt.setString(2, baseUser.getPassword());
        boolean isSuccessful = stmt.execute();
        if (isSuccessful) {
            ResultSet resultSet = stmt.getResultSet();
            while (resultSet != null && resultSet.next()) {
                System.out.println(resultSet.getString("nickName"));
            }
        } else {
            System.out.println("no success");
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return isSuccess;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值