DEV Community

Abu Ben Reaz
Abu Ben Reaz

Posted on

2

Function/Method to get DataTable from SQL Server Database in c#


Function/Method to get DataTable from SQL Server Database in c#


In this sample, you pass SQL String to the function and get the result in DataTable. You can use this function from anywhere of your application to get DataTable based on SQL String.



using System;


using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Data.SqlClient;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Windows.Forms;

namespace DBUtilities
{
 public class Program
 {
  public static void Main(string[] args)
  {
   //Declare the variable
   DataTable MyTable;
   //Calling the function to get the result in DataTable
   MyTable =GetTable("SELECT * FROM tblAccount”);
  }
  public static DataTable GetTable(string strSQL)
  {
   SqlConnection FillConn = new SqlConnection(YourConnetionString);
   System.Data.DataTable UserTable = new System.Data.DataTable();
   FillConn.Open();
   SqlCommand sqlCommand = new SqlCommand();
   sqlCommand.Connection = FillConn;
   sqlCommand.CommandText = strSQL;
   SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();
   sqlDataAdapter.SelectCommand = sqlCommand;
   sqlDataAdapter.Fill(UserTable);
   return UserTable;
  }
 }
}

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more