Pergunta

I'm trying to query data from an SQL table using C# using System.Data.SqlClient;. I'm able to SELECT * FROM table without problem. I suspect my problem may be due to data types, and perhaps unintentionally casting some variables incorrectly. The error I get is: Invalid attempt to read data when no data is present.

Further details:

In my SQL Table, Column1 and Column3 are of type int. Column2 and Column4 are of type char(1). Column5 is of type decimal(5,4).

Could you please help identify the problem in following code?

public void Score(List<Tuple<int, char>> myList)
    {
        int myColumn1 = myList[0].Item1;
        char myColumn2 = myList[0].Item2;
        int myColumn3 = myList[1].Item1;
        char myColumn4 = myList[1].Item2;

        myConnection.Open();

        SqlCommand myCommand = new SqlCommand("SELECT * FROM table" +
        " WHERE Column1 = " + myColumn1 + 
        " AND Column2 = '" + myColumn2 +
        "' AND Column3 = " + myColumn3 +
        " AND Column4 = '" + myColumn4 + "'", myConnection);

        SqlDataReader myReader = null;
        myReader = myCommand.ExecuteReader();

        Console.Out.WriteLine(myReader[5].ToString());         
    }

Thank you!

Foi útil?

Solução

After retrieving the data from the database, you have to Read it:

while (myReader.Read())
{
    Console.Out.WriteLine(myReader[5].ToString());
}

You can see an example on MSDN.

A couple other notes:

  • If myReader[5] might be null, then consider using Convert.ToString(myReader[5]). That'll return an empty string instead of throwing an exception.

  • If you're using .NET 4.5, there's an alternate syntax you could try: myReader.GetFieldValue<string>(5)

Outras dicas

Use paremeterized query to avoid sql injectioin

myCommand = new SqlCommand("SELECT * FROM table
        WHERE Column1=@column1
         AND Column2 =@myColumn2 
         AND Column3 = @myColumn3 
         AND Column4 =@myColumn4", myConnection);

  myCommand.Parameters.AddWithValue("@column1", value1);
  myCommand.Parameters.AddWithValue("@myColumn2", value2);
  myCommand.Parameters.AddWithValue("@myColumn3", value3);
  myCommand.Parameters.AddWithValue("@myColumn3", value4);

  using(SqlDataReader reader = myCommand.ExecuteReader())
  {
    while(reader.Read())
    {
      //code here
    }
  }
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top