Web Design that taps into the haromny and vision of your dreams.

Method to Query SQL Database and Return Data Reader

Query SQL Database and get a Data Reader

Written By on in C#

157 words, estimated reading time 1 minutes.

This handy little method will allow you to query a SQL Server database and will return a SqlDataReader that can be used in your code. This method encapsulates the connection and command components and enables your code to be a little neater with greater code reuse.

public static SqlDataReader queryDatabase(string queryString, string connectionString)
{
  SqlConnection con = new SqlConnection(connectionString);
  SqlCommand cmd = new SqlCommand(commandString, con);
  return cmd.ExecuteReader();
}

Usage

Include this method in you project and use it to query a database.

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Text;
 
namespace ConsoleApplication1
{
  class Program 
  {
    public static SqlDataReader queryDatabase(string queryString, string connectionString)
    {
      SqlConnection con = new SqlConnection(connectionString);
      SqlCommand cmd = new SqlCommand(queryString, con);
      con.Open();
      return cmd.ExecuteReader();
    }
 
    static void Main(string[] args)
    {
      string connectionString = @"Data Source=.SQLEXPRESS;AttachDbFilename=""C:SQL Server 2000 Sample DatabasesNORTHWND.MDF"";Integrated Security=True;Connect Timeout=30;User Instance=True";
 
      SqlDataReader dataReader = queryDatabase("SELECT * FROM Customers", connectionString);
      while (dataReader.Read())
      {
        Console.WriteLine(String.Format("{0} {1}", dataReader["CompanyName"], dataReader["ContactName"]));
      }
      dataReader.Close();
 
      dataReader = queryDatabase("UPDATE Customers SET ContactName = 'Jane Doe' WHERE CompanyName = 'Acme Inc'",  connectionString);
      dataReader.Close();
    }
  }
}

Last updated on: Friday 23rd June 2017

 

Comments

There are no comments for this post. Be the first!

 

Leave a Reply

Your email address will not be published.





If you find something abusive or that does not comply with our terms or guidelines please flag it as inappropriate.

Copyright © 2001-2018 Tim Trott, all rights reserved. Web Design by Azulia Designs

This web page is licensed for your personal, private, non-commercial use only.

Disclaimer, Privacy & LegalSitemapContact Me