Connecting to database with C#

Connect to database using C# and manipulate data from table.

Last updated:

Warning: Review and test in a non-production environment before running.

Back to results

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

namespace CountRows
{    
    class Program    
    {        
        static void Main(string[] args)        
        {            
            // Create a String to hold the database connection string.            
            // NOTE: Put in a real database connection string here or runtime won't work            

            string sdwConnectionString = @"Data Source = YourServer; Integrated Security=SSPI; Initial Catalog = YourDatabase;";             

            // Create a connection            
            SqlConnection sdwDBConnection = new SqlConnection(sdwConnectionString);             

            // Open the connection            
            sdwDBConnection.Open();             

            // Create a String to hold the query.            
            string query = "SELECT * FROM MIFALIM";             

            // Create a SqlCommand object and pass the constructor the connection string and the query string.            
            SqlCommand queryCommand = new SqlCommand(query, sdwDBConnection);             

            // Use the above SqlCommand object to create a SqlDataReader object.            
            SqlDataReader queryCommandReader = queryCommand.ExecuteReader();             

            // Create a DataTable object to hold all the data returned by the query.            
            DataTable dataTable = new DataTable();             

            // Use the DataTable.Load(SqlDataReader) function to put the results of the query into a DataTable.            
            dataTable.Load(queryCommandReader);             

            // Example 1 - Print your  Column Headers            
            String columns = string.Empty;            
            foreach (DataColumn column in dataTable.Columns)            
            {                
                columns += column.ColumnName + " | ";            
            }            Console.WriteLine(columns);             

            // Example 2 - Print the first 10 row of data            
            int topRows = 10;            
            for (int i = 0; i < topRows; i++)            
            {                
                String rowText = string.Empty;                
                foreach (DataColumn column in dataTable.Columns)                
                {                    
                rowText += dataTable.Rows[i][column.ColumnName] + " | ";                
                }                
                Console.WriteLine(rowText);            
            }             

            // Close the connection            
            sdwDBConnection.Close();        
        }    
    }
}