编程语言
首页 > 编程语言> > c#-无法从存储过程中获取数据

c#-无法从存储过程中获取数据

作者:互联网

我试图从C#代码中访问存储过程,但总是得到结果== -1.我不知道哪里出了问题.我已经搜索了很多,但没有找到任何解决方案.请查看我的代码段,并指导我做错了什么.

提前致谢.

C#代码:

using (SqlConnection connection = new SqlConnection(getConnectionString()))
using (SqlCommand command = new SqlCommand())
{
    Int32 rowsAffected;

    command.CommandText = "SP_LOGIN_GETUSERBYNAME";
    command.CommandType = CommandType.StoredProcedure;
    // command.Parameters.Add(new SqlParameter("@Email", userObj.email));
    // command.Parameters.Add("@Email", SqlDbType.VarChar).Value = userObj.email.Trim();
    command.Parameters.AddWithValue("@Email", userObj.email.ToString());
    command.Connection = connection;

    connection.Open();
    rowsAffected = command.ExecuteNonQuery();
    connection.Close();

    return rowsAffected;
}

连接字符串:

return "Data Source=MUNEEB-PC;Initial Catalog=HRPayRoll;User ID=sa; Password=sa";

存储过程代码:

CREATE PROCEDURE SP_LOGIN_GETUSERBYNAME
    @Email varchar(50)
AS
    SELECT *
    FROM [User]
    WHERE Email = @Email
GO

解决方法:

ExecuteNonQuery doc起;

For UPDATE, INSERT, and DELETE statements, the return value is the
number of rows affected by the command. When a trigger exists on a
table being inserted or updated, the return value includes the number
of rows affected by both the insert or update operation and the number
of rows affected by the trigger or triggers. For all other types of
statements, the return value is -1

由于您的命令是SELECT,因此将-1作为返回值是很正常的.

如果您想获得结果,可以改用ExecuteReader方法.

var reader = command.ExecuteReader();
while (reader.Read())
{
     // This will iterate your results line by line and
     // You can get columns with zero-based values like reader[0], reader[1] or
     // can use GetXXX methods of it like GetString(0) or GetInt32(1) etc.
}

标签:c,sql-server,stored-procedures,wcf-data-services
来源: https://codeday.me/bug/20191028/1950298.html