How to print in C # console a value extracted from sql server

0

I have this code, I just want to show a value that I get from a query to my DB in the console of C#

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Data;
    using System.Data.SqlClient;

    namespace PRUEBA
    {
        class Program
        {
            public object MessageBox { get; private set; }

            static void Main(string[] args)
            {

            }

            public void ConnectToSql()
            {

                SqlConnection con = new SqlConnection("Data Source=name;Integrated Security=true;");
                con.Open();
                SqlCommand com = new SqlCommand("SELECT ---", con);

                Console.WriteLine(com);

            }

        }
    }
    
asked by use2105 03.11.2016 в 16:27
source

1 answer

2

So far, all you do is set the query you want. You have to execute it and go through the possible results of this query. We use a SqlDataReader to obtain the execution of your query, then we make a cycle while where we go through the queries until there are no more records and we look for the column that we expect by registration FILA.

SqlConnection con = new SqlConnection("Data Source=name;Integrated Security=true;");
con.Open();
SqlCommand com = new SqlCommand("SELECT ---", con);
using(SqlDataReader reader = com.ExecuteReader()) 
{
    while (reader.Read()) 
    {
        //Debes saber bien que tipo de dato trae para convertirlo en caso que necesitaras por ejemplo :
        /*   
        int numero = Convert.ToInt32(reader["Columna"].ToString());
        */
        Console.WriteLine(reader["Columna"].ToString());
        Console.ReadLine();

    }

    con.Close();
}
    
answered by 03.11.2016 в 16:33