Sunday, March 10, 2019

Visual Studio - C# - Console - Hello World, Run SQL Query Example




 using System;  

 using System.Collections.Generic;  

 using System.Linq;  

 using System.Text;  

 using System.Threading.Tasks;  

 using System.Data.SqlClient;  

 namespace ConsoleApp1  

 {  

   class Program  

   {  

     static void Main(string[] args)  

     {  

       // The code provided will print ‘Hello World’ to the console.  

       // Press Ctrl+F5 (or go to Debug > Start Without Debugging) to run your app.  

       Console.WriteLine("Hello World!");  

       Console.ReadKey();  

       // Go to http://aka.ms/dotnet-get-started-console to continue learning how to build a console app!   

       string queryString = "SELECT * FROM [LSONE].[dbo].[COUNTRY]";  

       string connectionString = "Server=TEST;Database=;User Id=sa;Password=mypassword;";  

       using (SqlConnection connection = new SqlConnection(connectionString))  

       {  

         SqlCommand command = new SqlCommand(queryString, connection);  

         command.Parameters.AddWithValue("@tPatSName", "Your-Parm-Value");  

         connection.Open();  

         SqlDataReader reader = command.ExecuteReader();  

         try  

         {  

           while (reader.Read())  

           {  

             Console.WriteLine(String.Format("{0}, {1}",  

             reader["COUNTRYID"], reader["NAME"]));// etc  

             Console.ReadKey();  

           }  

         }  

         finally  

         {  

           // Always call Close when done reading.  

           reader.Close();  

         }  

       }  

     }  

   }  

 }  

No comments:

Post a Comment