Check if a record exists in the database

前端 未结 13 1706
借酒劲吻你
借酒劲吻你 2020-11-28 12:58

I am using these lines of code to check if the record exists or not.

SqlCommand check_User_Name = new SqlCommand(\"SELECT * FROM Table WHERE ([user] = \'\" +         


        
13条回答
  •  一整个雨季
    2020-11-28 13:17

    The ExecuteScalar method should be used when you are really sure your query returns only one value like below:

    SELECT ID FROM USERS WHERE USERNAME = 'SOMENAME'
    

    If you want the whole row then the below code should more appropriate.

    SqlCommand check_User_Name = new SqlCommand("SELECT * FROM Table WHERE ([user] = @user)" , conn);
    check_User_Name.Parameters.AddWithValue("@user", txtBox_UserName.Text);
    SqlDataReader reader = check_User_Name.ExecuteReader();
    if(reader.HasRows)
    {
       //User Exists
    }
    else
    {
       //User NOT Exists
    }
    

提交回复
热议问题