简体   繁体   English

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

[英]Unable to get data from stored procedure

I'm trying to hit the stored procedure from C# code but always get the result == -1. 我试图从C#代码中获取存储过程,但始终得到结果== -1。 I don't know where I went wrong. 我不知道哪里出错了。 I have searched a lot but didn't' find any solution. 我搜索了很多,但没有找到任何解决方案。 Please have a look into my code snippet and guide me what I'm doing wrong. 请查看我的代码片段并指导我做错了什么。

Thanks in advance. 提前致谢。

C# code: 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;
}

Connection string: 连接字符串:

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

Stored procedure code: 存储过程代码:

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

From ExecuteNonQuery doc; 来自ExecuteNonQuery doc;

For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. 对于UPDATE,INSERT和DELETE语句,返回值是受命令影响的行数。 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 对于所有其他类型的语句,返回值为-1

Since your command is SELECT, it is too normal to get -1 as a return value. 因为你的命令是SELECT,实在是正常的拿到-1作为返回值。

If you wanna reach your results, you can use ExecuteReader method instead. 如果要获得结果,可以使用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.
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM