Home >Database >Mysql Tutorial >How to Efficiently Import SQL Table Data into a C# DataTable?

How to Efficiently Import SQL Table Data into a C# DataTable?

Susan Sarandon
Susan SarandonOriginal
2025-01-11 21:52:43562browse

How to Efficiently Import SQL Table Data into a C# DataTable?

Import SQL table data into C# DataTable

In data processing, reading data from SQL table and converting it to C# DataTable is a common and important task. While inserting a DataTable into a SQL table is well documented, the process of extracting data from a SQL table into a DataTable may be less clear.

We can use the SqlDataAdapter method of the Fill class to accomplish this task. This method retrieves data from the specified table or query and populates the DataTable with the results.

Implementation method:

<code class="language-csharp">using System;
using System.Data;
using System.Data.SqlClient;

public class DataImporter
{
    // 创建一个DataTable来存储检索到的数据
    private DataTable dataTable = new DataTable();

    // 从SQL表中提取数据到DataTable的方法
    public void ImportData()
    {
        // 定义连接字符串
        string connString = @"Your connection string here";

        // 编写查询语句以从表中选择数据
        string query = "SELECT * FROM table";

        // 建立数据库连接
        using (SqlConnection conn = new SqlConnection(connString))
        {
            // 创建命令对象并执行查询
            using (SqlCommand cmd = new SqlCommand(query, conn))
            {
                conn.Open();

                // 创建数据适配器并使用查询结果填充DataTable
                using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                {
                    da.Fill(dataTable);
                }
            }
        }
    }
}</code>

After calling the ImportData method, dataTable will be populated with data retrieved from the SQL table. This data can then be accessed and processed in C# code.

This method ensures that the data in the SQL table can be efficiently and accurately imported into the C# DataTable for further analysis and operations.

The above is the detailed content of How to Efficiently Import SQL Table Data into a C# DataTable?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn