programing

C# 데이터 테이블로 SQL 테이블 읽기

iphone6s 2023. 4. 27. 21:57
반응형

C# 데이터 테이블로 SQL 테이블 읽기

SQL 테이블에 데이터 테이블을 삽입하는 것에 대한 게시물을 많이 읽었는데 SQL 테이블을 에 쉽게 가져올 수 있는 방법이 있습니까?NET 데이터 테이블?

여기, 이것을 시도해 보세요(이것은 단지 의사 코드일 뿐입니다.

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를 사용합니다.데이터 어댑터를 네트로 만들고 채우기를 사용하여 데이터 테이블을 가져옵니다.

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

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

업데이트된 답변 데이터 세트의 참고 사항은 사용되지 않습니다. (제 답변 이후에 나타남) 사용됩니다.

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

내 것보다 더 나은 것.

하지만 나는 엔티티 프레임워크를 검토할 것을 강력히 추천합니다...데이터 테이블과 데이터셋을 사용하는 것은 좋은 생각이 아닙니다.형식 안전성이 없으므로 실행 시에만 디버깅을 수행할 수 있습니다.강력한 유형의 컬렉션(LINQ2SQL 또는 엔티티 프레임워크를 사용하여 얻을 수 있음)을 사용하면 작업이 훨씬 쉬워집니다.

편집: 데이터 테이블 = 좋음, 데이터 세트 = 사악함.ADO를 사용하는 경우.그런 다음 일반적으로 ado.net 위에 있는 것처럼 이 두 가지 기술(EF, linq2sql, dapper, nhibernate 또는 month)을 모두 사용할 수 있습니다.코드 생성을 활용하여 적절한 수준의 추상화를 제공하면 스키마가 변경됨에 따라 모델을 훨씬 쉽게 업데이트할 수 있다는 이점이 있습니다.

ado.net 어댑터는 데이터베이스의 유형 정보를 표시하는 제공자를 사용합니다. 예를 들어 기본적으로 SQL 서버 제공자를 사용합니다.당신은 또한 - 예를 들어 - 포스트그레스 프로바이더를 플러그인할 수 있고 - 위와 같이 당신이 선택한 오름을 사용할 수 있도록 하는 유형 정보에 여전히 액세스할 수 있습니다 - 저는 마이크로소프트가 오라클 프로바이더도 제공한다고 믿습니다.이것의 전체 목적은 가능한 경우 데이터베이스 구현에서 추상화하는 것입니다.

벤더 독립 버전은 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보다 성능이 뛰어나다는 점을 혼동하지 않도록 쿼리가 모두 다릅니다).하지만 둘 사이의 차이는 질문에 달려 있었습니다.그 이유는Load행을 추가할 때 문서에서 행별로 다양한 제약 조건을 확인해야 합니다(이 방법은DataTable) 동안에 편한Fill데이터 테이블의 빠른 생성을 위해 설계된 DataAdapters에 있습니다.

중앙 집중화된 모델:어디서든 사용할 수 있습니다!

당신은 당신의 직무에서 이 클래스로 아래 형식을 호출하기만 하면 됩니다.

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

최신 버전의 C#(버전 8 이후)을 사용하는 경우 사용 문에 중괄호가 필요하지 않기 때문에 코드가 훨씬 더 단순해집니다.

var table = new DataTable();
using var da = new SqlDataAdapter(sql, connectionString);
da.Fill(table);     

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

반응형