Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
4 views
in SQL by (20.3k points)

I've read a lot of posts about inserting a DataTable into a SQL table, but is there an easy way to pull a SQL table into a .NET DataTable?

1 Answer

0 votes
by (40.7k points)

Try using the code given below:

using System;

using System.Data;

using System.Data.SqlClient;

public class PullDataTest

{

    // your data table

    private DataTable dataTable = new DataTable();

  public PullDataTest()

    {

    }

    // your method to pull data from database to datatable   

    public void PullData()

    {

        string connString = @"your connection string here";

        string query = "select * from table";

        SqlConnection conn = new SqlConnection(connString);        

        SqlCommand cmd = new SqlCommand(query, conn);

        conn.Open();

        // create data adapter

        SqlDataAdapter da = new SqlDataAdapter(cmd);

        // this will query your database and return the result to your datatable

        da.Fill(dataTable);

        conn.Close();

        da.Dispose();

    }

}

Enroll yourself in the best sql courses to learn in-depth about SQL statements, queries and become proficient in SQL.

Related questions

0 votes
2 answers
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
3 answers

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...