SQL error in casting from int to string

0

I have a method where I need to return the ID ( integer ) of a particular record whose name passes as a parameter, however Visual Studio points to the following error:

  

Object reference not set to an instance of an object

This error occurs in the commented line:

public int buscarIdPorNome(string nomeSetor) //Busca id do setor pelo nome
    {
        int idSetor = 0;

        con = dal.conectar();//Conectando com o BD - retorna "new SqlConnection(connectionStringBuilder.ToString());"
        string cmdText = "SELECT (ID_Setor) FROM dbo.Setor WHERE Nome_STOR = @Nome_STOR"; //Definindo comando
        SqlCommand cmd = new SqlCommand(cmdText, con); //Adicionando comando

        cmd.Parameters.AddWithValue("@Nome_STOR", nomeSetor);

        con.Open();
        idSetor = (Int32)cmd.ExecuteScalar(); //Dando erro

        if (con != null)
        {
            con.Close(); //Fechando conexão
        }

        return idSetor;

    }

I have tried to change the code that is giving error, but I did not succeed, it still points to the same error. Command I tried:

idSetor = int.Parse(cmd.ExecuteScalar().ToString());

Remembering that the object con is a SQLConnection and the dal.conectar(); method is only creating StringBuilder , setting the server and the database, but I do not think it's relevant for this error to put the code here.

    
asked by anonymous 13.05.2018 / 18:08

1 answer

1

There's nothing wrong with your code, I replicated it and it works normally (check the print).

Your problem is in your Query, have you tried to reproduce your query in the database?

DECLARE @Nome_STOR varchar(100)
SET @Nome_STOR = 'Nome do Setor'
SELECT (ID_Setor) FROM dbo.Setor WHERE Nome_STOR = @Nome_STOR

AsasuggestionusetheusingclauseinyourSqlConnection:

using(varcon=newSqlConnection("Persist Security Info=False;Integrated Security=true;Initial Catalog=CourseDB;server=(local)"))
{
    string nomeSetor = "Thiago";
    string cmdText = "SELECT (Id) FROM dbo.Student WHERE Name = @Nome_STOR"; //Definindo comando
    SqlCommand cmd = new SqlCommand(cmdText, con); //Adicionando comando

    cmd.Parameters.AddWithValue("@Nome_STOR", nomeSetor);

    con.Open();
    idSetor = (Int32)cmd.ExecuteScalar(); //Dando erro
}
    
13.05.2018 / 20:16