using a stored procedure for login in c#
If I run a store procedure with two parameter values (admin, admin) (parameters : admin, admin) I get the following message :
Session_UID User_Group_Name Sys_User_Name ------------------------------------ -------------------------------------------------- - NULLAdministratorsNTMSAdmin No rows affected. (1 row(s) returned) @RETURN_VALUE = 0 Finished running [dbo].[p_SYS_Login].
To get the same message in c# I used the code following :
string strConnection = Settings.Default.ConnectionString;
using (SqlConnection conn = new SqlConnection(strConnection))
{
using (SqlCommand cmd = new SqlCommand())
{
SqlDataReader rdr = null;
cmd.Connection = conn;
cmd.CommandText = "p_SYS_Login";
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter paramReturnValue = new SqlParameter();
paramReturnValue.ParameterName = "@RETURN_VALUE";
paramReturnValue.SqlDbType = SqlDbType.Int;
paramReturnValue.SourceColumn = null;
paramReturnValue.Direction = ParameterDirection.ReturnValue;
cmd.Parameters.Add(paramReturnValue开发者_开发技巧);
cmd.Parameters.Add(paramGroupName);
cmd.Parameters.Add(paramUserName);
cmd.Parameters.AddWithValue("@Sys_Login", "admin");
cmd.Parameters.AddWithValue("@Sys_Password", "admin");
try
{
conn.Open();
rdr = cmd.ExecuteReader();
string test = (string)cmd.Parameters["@RETURN_VALUE"].Value;
while (rdr.Read())
{
Console.WriteLine("test : " + rdr[0]);
}
}
catch (Exception ex)
{
string message = ex.Message;
string caption = "MAVIS Exception";
MessageBoxButtons buttons = MessageBoxButtons.OK;
MessageBox.Show(
message,
caption,
buttons,
MessageBoxIcon.Warning,
MessageBoxDefaultButton.Button1);
}
finally
{
cmd.Dispose();
conn.Close();
}
}
}
but I get nothing in SqlDataReader rdr ; is there something I am missing ?
The value at column 0 Session_UID
is null as you have shown so I think this may be the reason you are not getting anything here:
Console.WriteLine("test : " + rdr[0]);
but then as an aside you might get Null reference exception.
Still why don't you try this:
Console.WriteLine("Return Value: " + test);
while(rdr.Read()){
Console.WriteLine("test: " + rdr[0]+" " + rdr[1]+ " " + rdr[1]);
}
If you want to get back a return value, but no result rows, you shouldn't be using the .ExecuteReader()
but rather the .ExecuteNonQuery()
call:
try
{
conn.Open();
object result = cmd.ExecuteNonQuery();
string test = (string)cmd.Parameters["@RETURN_VALUE"].Value;
conn.Close();
}
catch (Exception ex)
{
....
}
Also, since you have your SqlCommand
in a using....
block, there's really no point in the finally
block of your try - the using
statement will take care of that already.
精彩评论