IT

SQL 테이블을 C # DataTable로 읽기

lottoking 2020. 10. 9. 08:39

SQL 테이블을 C # DataTable로 읽기


DataTable을 SQL 테이블에 삽입하는 방법에 대한 많은 게시물을 읽었지만 SQL 테이블을 .NET DataTable로 가져 오는 쉬운 방법이 있습니까?


여기,이를 시도하십시오 (이것은 단지 의사 코드입니다)

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();
    }
}

var table = new DataTable();    
using (var da = new SqlDataAdapter("SELECT * FROM mytable", "connection string"))
{      
    da.Fill(table);
}

많은 방법.

ADO.Net을 사용하고 데이터 어댑터에 채우기를 사용하여 DataTable을 가져옵니다.

using (SqlDataAdapter dataAdapter
    = new SqlDataAdapter ("SELECT blah FROM blahblah ", sqlConn))
{
    // create the DataSet 
    DataSet dataSet = new DataSet(); 
    // fill the DataSet using our DataAdapter 
    dataAdapter.Fill (dataSet);
}

그런 다음 데이터 세트에서 데이터 테이블을 수 있습니다.

upvoted 답변 데이터 세트의 메모는 사용되지 않습니다. (내 답게 나타남)

// create data adapter
SqlDataAdapter da = new SqlDataAdapter(cmd);
// this will query your database and return the result to your datatable
da.Fill(dataTable);

내 것보다 낫다.

하지만 멀리 보는 프레임을 보는 것이 좋습니다. 데이터 테이블과 데이터 세트를 사용하는 것은 좋은 생각이 아닙니다. 유형 공연이 수행됩니다. 강력한 형식의 컬렉션 (LINQ2SQL 또는 엔터티 프레임 워크를 사용하여 얻을 수 있음)을 사용하면 작업이 훨씬 적게 처리됩니다.

편집 : 아마도 나는 명확하지 사고를 것입니다 : Datatables = good, datasets = evil. ADO.Net을 사용하는 경우 일반적으로 ado.net 위에 위치하는 기술 (EF, linq2sql, dapper, nhibernate, orm)을 모두 사용할 수 있습니다. 그 결과 수있는 이점은 코드 생성을 활용하여 적절한 수준의 추상화가 제공되는 경우 스키마 변경에 따라 모델을 쉽게 업데이트 할 수있는 것입니다.

ado.net 어댑터는 데이터베이스의 유형 정보를 노출하는 공급자를 사용합니다. 예를 들어 기본적으로 SQL 서버 공급자를 사용합니다. 예를 들어 devart 포스트그레스 공급자를 강화할 수도 있습니다. 그러면 유형 정보에 계속 액세스 할 수 있습니다. 위와 같이 선택하거나 사용할 수 있습니다. (거의 고통없이-몇 가지 단점이 있습니다). Microsoft도 오라클 공급자를 제공합니다. 이것의 전적인 목적은 가능한 경우 데이터베이스 구현에서 추상화하는 것입니다.


공급 업체 독립 버전, ADO.NET 인터페이스 의존합니다. 2 가지 방법 :

public DataTable Read1<T>(string query) where T : IDbConnection, new()
{
    using (var conn = new T())
    {
        using (var cmd = conn.CreateCommand())
        {
            cmd.CommandText = query;
            cmd.Connection.ConnectionString = _connectionString;
            cmd.Connection.Open();
            var table = new DataTable();
            table.Load(cmd.ExecuteReader());
            return table;
        }
    }
}

public DataTable Read2<S, T>(string query) where S : IDbConnection, new() 
                                           where T : IDbDataAdapter, IDisposable, new()
{
    using (var conn = new S())
    {
        using (var da = new T())
        {
            using (da.SelectCommand = conn.CreateCommand())
            {
                da.SelectCommand.CommandText = query;
                da.SelectCommand.Connection.ConnectionString = _connectionString;
                DataSet ds = new DataSet(); //conn is opened by dataadapter
                da.Fill(ds);
                return ds.Tables[0];
            }
        }
    }
}

나는 몇 가지 성능 테스트를 수행 두 번째 접근 방식은 항상 첫 번째 접근 방식보다 성능이 우수했습니다.

Stopwatch sw = Stopwatch.StartNew();
DataTable dt = null;
for (int i = 0; i < 100; i++)
{
    dt = Read1<MySqlConnection>(query); // ~9800ms
    dt = Read2<MySqlConnection, MySqlDataAdapter>(query); // ~2300ms

    dt = Read1<SQLiteConnection>(query); // ~4000ms
    dt = Read2<SQLiteConnection, SQLiteDataAdapter>(query); // ~2000ms

    dt = Read1<SqlCeConnection>(query); // ~5700ms
    dt = Read2<SqlCeConnection, SqlCeDataAdapter>(query); // ~5700ms

    dt = Read1<SqlConnection>(query); // ~850ms
    dt = Read2<SqlConnection, SqlDataAdapter>(query); // ~600ms

    dt = Read1<VistaDBConnection>(query); // ~3900ms
    dt = Read2<VistaDBConnection, VistaDBDataAdapter>(query); // ~3700ms
}
sw.Stop();
MessageBox.Show(sw.Elapsed.TotalMilliseconds.ToString());

Read1보기에는 더 좋아 보이지만 데이터 어댑터 성능이 더 좋습니다 (하나의 db가 다른 db보다 성능이 뛰어나다는 것을 혼동하지 말고 쿼리가 모두 달랐습니다). 하지만 둘의 차이는 쿼리에 따라 다릅니다. 그 이유 는 DataTables의 빠른 생성을 위해 설계된 DataAdapters에있는 동안 행을 추가 할 때 문서에서Load 행별로 다양한 제약 조건을 확인해야하기 때문일 수 있습니다 (에 메서드 ) .DataTableFill


중앙 집중 형 모델 : 어디서나 사용할 수 있습니다!

함수에서이 클래스로 아래 형식을 호출하면됩니다.

DataSet ds = new DataSet();
SqlParameter[] p = new SqlParameter[1];
string Query = "Describe Query Information/either sp, text or TableDirect";
DbConnectionHelper dbh = new DbConnectionHelper ();
ds = dbh. DBConnection("Here you use your Table Name", p , string Query, CommandType.StoredProcedure);

그게 다야. 완벽한 방법입니다.

public class DbConnectionHelper {
   public DataSet DBConnection(string TableName, SqlParameter[] p, string Query, CommandType cmdText) {
    string connString = @ "your connection string here";
    //Object Declaration
    DataSet ds = new DataSet();
    SqlConnection con = new SqlConnection();
    SqlCommand cmd = new SqlCommand();
    SqlDataAdapter sda = new SqlDataAdapter();
    try {
     //Get Connection string and Make Connection
     con.ConnectionString = connString; //Get the Connection String
     if (con.State == ConnectionState.Closed) {
      con.Open(); //Connection Open
     }
     if (cmdText == CommandType.StoredProcedure) //Type : Stored Procedure
     {
      cmd.CommandType = CommandType.StoredProcedure;
      cmd.CommandText = Query;
      if (p.Length > 0) // If Any parameter is there means, we need to add.
      {
       for (int i = 0; i < p.Length; i++) {
        cmd.Parameters.Add(p[i]);
       }
      }
     }
     if (cmdText == CommandType.Text) // Type : Text
     {
      cmd.CommandType = CommandType.Text;
      cmd.CommandText = Query;
     }
     if (cmdText == CommandType.TableDirect) //Type: Table Direct
     {
      cmd.CommandType = CommandType.Text;
      cmd.CommandText = Query;
     }
     cmd.Connection = con; //Get Connection in Command
     sda.SelectCommand = cmd; // Select Command From Command to SqlDataAdaptor
     sda.Fill(ds, TableName); // Execute Query and Get Result into DataSet
     con.Close(); //Connection Close
    } catch (Exception ex) {

     throw ex; //Here you need to handle Exception
    }
    return ds;
   }
  }

참고 URL : https://stackoverflow.com/questions/6073382/read-sql-table-into-c-sharp-datatable