简体   繁体   English

如何从DataTable中提取数据?

[英]How do I extract data from a DataTable?

I have a DataTable that is filled in from an SQL query to a local database, but I don't know how to extract data from it.我有一个从 SQL 查询填充到本地数据库的DataTable ,但我不知道如何从中提取数据。 Main method (in test program):主要方法(在​​测试程序中):

static void Main(string[] args)
{
    const string connectionString = "server=localhost\\SQLExpress;database=master;integrated Security=SSPI;";
    DataTable table = new DataTable("allPrograms");

    using (var conn = new SqlConnection(connectionString))
    {
        Console.WriteLine("connection created successfuly");

        string command = "SELECT * FROM Programs";

        using (var cmd = new SqlCommand(command, conn))
        {
            Console.WriteLine("command created successfuly");

            SqlDataAdapter adapt = new SqlDataAdapter(cmd);

            conn.Open(); 
            Console.WriteLine("connection opened successfuly");
            adapt.Fill(table);
            conn.Close();
            Console.WriteLine("connection closed successfuly");
        }
    }

    Console.Read();
}

The command I used to create the tables in my database:我用来在我的数据库中创建表的命令:

create table programs
(
    progid int primary key identity(1,1),
    name nvarchar(255),
    description nvarchar(500),
    iconFile nvarchar(255),
    installScript nvarchar(255)
)

How can I extract data from the DataTable into a form meaningful to use?如何将DataTable提取到有意义的形式中以使用?

The DataTable has a collection .Rows of DataRow elements. DataTable 有一个DataRow 元素的集合.Rows

Each DataRow corresponds to one row in your database, and contains a collection of columns.每个 DataRow 对应于数据库中的一行,并包含一组列。

In order to access a single value, do something like this:要访问单个值,请执行以下操作:

 foreach(DataRow row in YourDataTable.Rows)
 { 
     string name = row["name"].ToString();
     string description = row["description"].ToString();
     string icoFileName = row["iconFile"].ToString();
     string installScript = row["installScript"].ToString();
 }

You can set the datatable as a datasource to many elements.您可以将数据表设置为许多元素的数据源。

For eg例如

gridView网格视图

repeater中继器

datalist数据列表

etc etc等等等等

If you need to extract data from each row then you can use如果您需要从每一行中提取数据,那么您可以使用

table.rows[rowindex][columnindex]

or要么

if you know the column name如果你知道列名

table.rows[rowindex][columnname]

If you need to iterate the table then you can either use a for loop or a foreach loop like如果您需要迭代表,那么您可以使用 for 循环或 foreach 循环,例如

for ( int i = 0; i < table.rows.length; i ++ )
{
    string name = table.rows[i]["columnname"].ToString();
}

foreach ( DataRow dr in table.Rows )
{
    string name = dr["columnname"].ToString();
}

The simplest way to extract data from a DataTable when you have multiple data types (not just strings) is to use the Field<T> extension method available in the System.Data.DataSetExtensions assembly.当您有多种数据类型(不仅仅是字符串)时,从DataTable提取数据的最简单方法是使用System.Data.DataSetExtensions程序集中提供的Field<T>扩展方法。

var id = row.Field<int>("ID");         // extract and parse int
var name = row.Field<string>("Name");  // extract string

From MSDN , the Field<T> method:MSDNField<T>方法:

Provides strongly-typed access to each of the column values in the DataRow.提供对 DataRow 中每个列值的强类型访问。

This means that when you specify the type it will validate and unbox the object.这意味着当您指定类型时,它将验证并取消装箱对象。

For example:例如:

// iterate over the rows of the datatable
foreach (var row in table.AsEnumerable())  // AsEnumerable() returns IEnumerable<DataRow>
{
    var id = row.Field<int>("ID");                           // int
    var name = row.Field<string>("Name");                    // string
    var orderValue = row.Field<decimal>("OrderValue");       // decimal
    var interestRate = row.Field<double>("InterestRate");    // double
    var isActive = row.Field<bool>("Active");                // bool
    var orderDate = row.Field<DateTime>("OrderDate");        // DateTime
}

It also supports nullable types:它还支持可为空类型:

DateTime? date = row.Field<DateTime?>("DateColumn");

This can simplify extracting data from DataTable as it removes the need to explicitly convert or parse the object into the correct types.这可以简化从DataTable提取数据的过程,因为它消除了将对象显式转换或解析为正确类型的需要。

Please consider using some code like this:请考虑使用一些这样的代码:

SqlDataReader reader = command.ExecuteReader();
int numRows = 0;
DataTable dt = new DataTable();

dt.Load(reader);
numRows = dt.Rows.Count;

string attended_type = "";

for (int index = 0; index < numRows; index++)
{
    attended_type = dt.Rows[indice2]["columnname"].ToString();
}

reader.Close();

Unless you have a specific reason to do raw ado.net I would have a look at using an ORM (object relational mapper) like nHibernate or LINQ to SQL.除非您有特定的理由使用原始 ado.net,否则我会考虑使用 ORM(对象关系映射器),例如 nHibernate 或 LINQ to SQL。 That way you can query the database and retrieve objects to work with which are strongly typed and easier to work with IMHO.通过这种方式,您可以查询数据库并检索要使用的对象,这些对象是强类型的并且更易于使用恕我直言。

  var table = Tables[0]; //get first table from Dataset
  foreach (DataRow row in table.Rows)
     {
       foreach (var item in row.ItemArray)
         {
            console.Write("Value:"+item);
         }
     }

Please, note that Open and Close the connection is not necessary when using DataAdapter.请注意,使用 DataAdapter 时不需要打开和关闭连接。

So I suggest please update this code and remove the open and close of the connection:所以我建议请更新此代码并删除连接的打开和关闭:

        SqlDataAdapter adapt = new SqlDataAdapter(cmd);

conn.Open(); conn.Open(); // this line of code is uncessessary // 这行代码是不必要的

        Console.WriteLine("connection opened successfuly");
        adapt.Fill(table);

conn.Close(); conn.Close(); // this line of code is uncessessary // 这行代码是不必要的

        Console.WriteLine("connection closed successfuly");

Reference Documentation 参考文档

The code shown in this example does not explicitly open and close the Connection.此示例中显示的代码未显式打开和关闭连接。 The Fill method implicitly opens the Connection that the DataAdapter is using if it finds that the connection is not already open.如果发现连接尚未打开,Fill 方法会隐式打开 DataAdapter 正在使用的连接。 If Fill opened the connection, it also closes the connection when Fill is finished.如果 Fill 打开了连接,它也会在 Fill 完成时关闭连接。 This can simplify your code when you deal with a single operation such as a Fill or an Update.当您处理诸如填充或更新之类的单个操作时,这可以简化您的代码。 However, if you are performing multiple operations that require an open connection, you can improve the performance of your application by explicitly calling the Open method of the Connection, performing the operations against the data source, and then calling the Close method of the Connection.但是,如果您正在执行需要打开连接的多个操作,则可以通过显式调用 Connection 的 Open 方法,对数据源执行操作,然后调用 Connection 的 Close 方法来提高应用程序的性能。 You should try to keep connections to the data source open as briefly as possible to free resources for use by other client applications.您应该尝试尽可能短暂地保持与数据源的连接打开,以释放资源供其他客户端应用程序使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM