无法通过给定的用户名找到ID

时间:2018-11-10 07:08:14

标签: c# sql .net

我正在尝试通过用户名从名为userDataTbl(在我的MySQL数据库中)的用户表中获取用户ID。但是,当我运行下面的代码时,它始终返回-1,结果参数保持为-1,就好像找不到用户一样。

我还使用了下面的方法来检查表中是否已经存在用户名-然后我只是检查结果是否大于0以返回该用户名是否存在,否则返回不存在,但是即使我在表中放置了确实存在的名称,它也在那里不起作用,结果仍为-1。我已经尝试调试,但是它并没有告诉我太多信息,因为它并没有真正告诉我计算机在查询中的功能,因此我将知道它的问题所在。 这是代码:

//returns a user id according to a name
public int theId(string name)
{
    SqlCommand command2 = new SqlCommand("Select userId from dbo.userDataTbl where userName=@username", this.connection);
    command2.Parameters.AddWithValue("@username", name);
    int result = command2.ExecuteNonQuery();
    if (result > 0)
    {
        SqlDataReader reader = command2.ExecuteReader();
        reader.Read(); // we have only 1 row
        try
        {
            string foundId = String.Format("{0}", reader["userId"]);
            int id = Convert.ToInt32(foundId);
            return id;
        }
        catch
        {
            return 0;
        }
    }
    else
    {
        return -1;
    }
}

我将非常感谢您的帮助,这对我来说真的很重要。

2 个答案:

答案 0 :(得分:1)

基于https://3v4l.org/mvBYI

  

对于UPDATE,INSERT和DELETE语句,返回值是该命令影响的行数。当要插入或更新的表上存在触发器时,返回值包括受插入或更新操作影响的行数以及受一个或多个触发器影响的行数。对于所有其他类型的语句,返回值为-1。如果发生回滚,则返回值也为-1。

如果要获取受SELECT命令影响的行数并将其保存到int变量,则可以使用MSDNCount

"SELECT COUNT(userId)..."
var result = (int)command2.ExecuteScalar();

答案 1 :(得分:0)

我认为int result = command2.ExecuteNonQuery();行会导致问题,因为您删除了该行,更改了以下代码并运行

public int theId(string name)
{
    SqlCommand command2 = new SqlCommand("Select userId from dbo.userDataTbl where userName=@username", this.connection);
    command2.Parameters.AddWithValue("@username", name);
    this.connection.open();
    try
    {
        SqlDataReader reader = command2.ExecuteReader();
        if(reader.HasRows)
        {
            while(reader.Read())
            {
                string foundId = String.Format("{0}", reader["userId"]);
                int id = Convert.ToInt32(foundId);
                return id; 
            }
        }
        else
        {
            return -1;
        }
    }
    catch(Exception ex)
    {

    }                
}

希望这对您有帮助-编码愉快!!