A union of curiosity and data science

Knowledgebase and brain dump of a database engineer


C# Loop through sql server database recordset with SqlClient

Code : 

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

namespace MyNamespace
{
    class Program
    {
            static void Main(string[] args) {

            string connetionString = "Data Source=<servername>;Initial Catalog=<database>;User ID=<user_id>;Password=<password>";
            SqlConnection connection = new SqlConnection(connetionString);
            connection.Open();

            string sql = "select top 10 * from information_schema.tables";

            SqlCommand command = new SqlCommand(sql, connection);
            command.CommandTimeout = 600;
            SqlDataReader dataReader = command.ExecuteReader();

            while (dataReader.Read())
            {
              Console.WriteLine(dataReader["table_name"].ToString());
            }
            dataReader.Close();
            command.Dispose();
            connection.Close();
            
            Console.ReadKey();
        }

 

Add comment