Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read SQL Table into C# DataTable

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?

like image 854
Will Avatar asked May 20 '11 14:05

Will


People also ask

What is SqlCommand in C#?

A SqlCommand object allows you to specify what type of interaction you want to perform with a database. For example, you can do select, insert, modify, and delete commands on rows of data in a database table.

Which database to use with C#?

The most common databases used in C# are Microsoft SQL Server and Oracle. The following is done to work with databases.

Does C# work with SQL?

C# SQL can work with databases such as Oracle and Microsoft SQL Server. This C# database tutorial has all the commands which are required to work with databases. This involves establishing a connection to the database. You can perform operations such as select, update, insert and delete using the commands in C#.


2 Answers

Here, give this a shot (this is just a pseudocode)

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();     } } 
like image 127
yonan2236 Avatar answered Oct 12 '22 10:10

yonan2236


var table = new DataTable();     using (var da = new SqlDataAdapter("SELECT * FROM mytable", "connection string")) {           da.Fill(table); } 
like image 27
Tim Rogers Avatar answered Oct 12 '22 11:10

Tim Rogers