这是我的程序:
DECLARE @ReturnValue int
SELECT @ReturnValue = idUser
FROM Users
WHERE Alias = @UserAlias AND Password = @UserPassword
RETURN @ReturnValue
这是我的C#代码,我希望我可以从程序中检索该值:
TeamPWSecureBD.Open(); //Open SQL Connection
string alias = textBoxUsernameLogin.Text.Trim();
string pass = textBoxPasswordLogin.Text;
SqlCommand LoginVerify = new SqlCommand("_spUserVerify", TeamPWSecureBD);
LoginVerify.CommandType = CommandType.StoredProcedure;
LoginVerify.Parameters.AddWithValue("@UserAlias", alias);
LoginVerify.Parameters.AddWithValue("@UserPassword", pass);
SqlDataReader UserVerify = LoginVerify.ExecuteReader();
//Se o valor retornado pelo sp for 0 significa que o user não existe.
//O sp retorna o id do utilizador se o username e a password estiverem corretas.
//O id de utilizador menor é o 7.
if (Convert.ToInt32(UserVerify.GetSqlValue(0)) == 0)
MessageBox.Show("Invalid username/password.", "Login Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
else
{
GlobalVariables.UserLoggedIn = Convert.ToInt32(UserVerify.GetSqlValue(0));
PWLists MainForm = new PWLists();
MainForm.ShowDialog();
this.Close();
}
当我在SQL Server中执行该过程时,返回的值是正确的。
但是一旦我尝试在表单中阅读它,它会崩溃并出现错误:
无数据存在时读取无效
答案 0 :(得分:1)
尝试:
SELECT @ReturnValue
而不是:
RETURN @ReturnValue
答案 1 :(得分:0)
如果要捕获存储过程执行的RETURN语句的值,则需要在SqlCommand中添加另一个参数
SqlParameter r = LoginVerify.Parameters.Add("@return", SqlDbType.Int);
r.Direction = ParameterDirection.ReturnValue;
r.Value = 0;
SqlDataReader UserVerify = LoginVerify.ExecuteReader();
// Now you need to complete the reading from the UserVerify reader and
// finally you can catch the return value
.....
UserVerify.Close();
int result = (int)r.Value;
但是,考虑到StoredProcedure的代码,我认为您可以简单地避免声明另一个参数以及SqlDataReader,因为您似乎只返回一行包含一个字段。 ExecuteScalar的确切范围...
SP现在只是一个选择
SELECT idUser FROM Users
WHERE Alias = @UserAlias AND Password = @UserPassword
并且检索idUser
的代码是
object result = LoginVerify.ExecuteScalar();
if (result == null)
MessageBox.Show("Invalid username/password.", "Login Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
else
{
GlobalVariables.UserLoggedIn = Convert.ToInt32(result);
PWLists MainForm = new PWLists();
MainForm.ShowDialog();
this.Close();
}