Good day. There is a table in the database, there are 4 columns in the table: Name, Date, Code, INN. I need to output using SQL query Name, Date, Code to the console. How to display three column values ​​at once select Name, Date, Code from tRefuseTable where inn = '{0}'? I tried to display only Name

string ConString = "connstring;"; using (SqlConnection connection = new SqlConnection(ConString)) { using (SqlCommand command = connection.CreateCommand()) { command.CommandText = string.Format(@"select Name from tRefuseTable where inn='{0}'", item.INN_Legal);//текст запроса connection.Open(); SqlDataReader reader = command.ExecuteReader(); while (reader.Read()) { Console.WriteLine(reader[0].ToString() ) ;//вывод результата на консоль } } } 
  • 2
    Well, correct the request - add the necessary columns to it, and then take reader[0] , reader[1] , reader[2] (and better reader["Name"] , etc.) - Andrey NOP
  • Another option is to use the appropriate GetXXX(...) method instead of the indexer, for example reader.GetString(0) - Andrey NOP

1 answer 1

For C # 6:

 command.CommandText = string.Format(@"select Name, Date, Code from tRefuseTable where inn='{0}'", item.INN_Legal);//текст запроса connection.Open(); SqlDataReader reader = command.ExecuteReader(); while (reader.Read()) { Console.WriteLine($"Name={reader[0]}, Date={reader[1]}, Code={reader[2]}"); } 

For previous versions:

 Console.WriteLine(string.Format("Name={0}, Date={1}, Code={2}", reader[0], reader[1], reader[2])); 

or even easier:

 Console.WriteLine("Name={0}, Date={1}, Code={2}", reader[0], reader[1], reader[2]); 

Also, to avoid potential SQL injections and allow the SQL server to cache query execution plans, it is better to use parameterized database queries.

 string sqlExpression = "select Name, Date, Code from tRefuseTable where inn=@inn"; using (SqlConnection connection = new SqlConnection(ConString)) { using (SqlCommand command = new SqlCommand(sqlExpression, connection)) { connection.Open(); SqlParameter nameParam = new SqlParameter("@inn", item.INN_Legal); command.Parameters.Add(nameParam); SqlDataReader reader = command.ExecuteReader(); while (reader.Read()) { Console.WriteLine($"Name={reader[0]}, Date={reader[1]}, Code={reader[2]}"); } } } 

On the topic of parameterization, see also:

  • @Bald Oh, exactly. Thanks, corrected. - AK
  • Hmm, since we decided to give an answer - write how to form parametrized queries correctly, and not by gluing together lines - Andrey NOP
  • 2
    Well, Console.WriteLine already has a string.Format inside, there’s no need to write it again: Console.WriteLine("Name={0}, Date={1}, Code={2}", reader[0], reader[1], reader[2]); . In the wrong place, you took advantage of the interpolation of strings - Andrew NOP