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

前端 未结 5 455
心在旅途
心在旅途 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:30

    You should do a count(1) on the table instead of a select * and then executescalar to get that integer value.

    Using your existing code I would change it to be:

    using (SqlConnection sqlConnection = dbUtil.GetSqlConnection(dbUtil.GetConnectionStringByName("NonConnectionString")))
            {
                using (SqlCommand sqlCommand = new SqlCommand("SELECT count(1) from users where user_name = 'Adam' AND password = '123456'", sqlConnection))
                {
                    sqlresult = sqlCommand.ExecuteNonQuery();
                }
            }
    

    Please note that I have used equals values instead of like values.

    Also if I were do to this I would change your inline sql to use a stored procedure.

提交回复
热议问题