Check if record in a table exist in a database through ExecuteNonQuery

前端 未结 5 461
心在旅途
心在旅途 2020-12-03 14:06

in my program i need to check if a record in the database already exists in the table using the if statement. using c# i am trying to do this through an sql con

5条回答
  •  鱼传尺愫
    2020-12-03 14:31

    If you want to check if the user exists, you have to change your sql and use COUNT or EXISTS:

    So instead of

    SELECT * from users where user_name like 'Adam' AND password like '123456'
    

    this

    SELECT COUNT(*) from users where user_name like 'Adam' AND password like '123456'
    

    Now you can use ExecuteScalar to retrieve the count of users with this username and password:

    int userCount = (int) sqlCommand.ExecuteScalar();
    if(userCount > 0)
        // user exists ....
    

    Note that you should use sql-parameters to prevent sql-injection:

    using (SqlCommand sqlCommand = new SqlCommand("SELECT COUNT(*) from users where user_name like @username AND password like @password", sqlConnection))
    {
        sqlConnection.Open();
        sqlCommand.Parameters.AddWithValue("@username", userName);
        sqlCommand.Parameters.AddWithValue("@password", passWord);
        int userCount = (int) sqlCommand.ExecuteScalar();
        ...
    }
    

提交回复
热议问题