如何从数据表中提取数据?


78

我有一个DataTable从SQL查询到本地数据库的数据,但是我不知道如何从中提取数据。主要方法(在​​测试程序中):

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

我用来在数据库中创建表的命令:

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

如何从中提取数据DataTable到有意义的表单中?

Answers:


157

DataTable具有.RowsDataRow元素的集合。

每个DataRow对应于数据库中的一行,并包含一组列。

为了访问单个值,请执行以下操作:

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

2
我知道这是一个旧答案,但是您是否不需要在foreach循环中进行强制转换以允许建立索引?在将代码更改为以下代码之前,我无法执行以下操作:foreach(YourDataTable.Rows.Cast <DataRow>()中的DataRow行)...
awh112 2015年

1
甚至是较旧的注释,但无需强制转换:foreach有效,因为它Rows是一个集合(DataRowCollection)。但是,.Cast<DataRow>()如果要使用某些Linq方法(.Where()例如,),则需要使用。
安德森·皮门特尔

24

您可以将数据表设置为许多元素的数据源。

例如

网格视图

中继器

资料清单

如果需要从每一行提取数据,则可以使用

table.rows[rowindex][columnindex]

要么

如果您知道列名

table.rows[rowindex][columnname]

如果您需要迭代表,则可以使用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();
}

的foreach(DataRow的博士表)table.Rows
StampedeXV

7

DataTable当您具有多种数据类型(不仅仅是字符串)时,从中提取数据的最简单方法是使用Field<T>程序集中可用的扩展方法System.Data.DataSetExtensions

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

MSDN中Field<T>方法:

提供对DataRow中每个列值的强类型访问。

这意味着,当您指定类型时,它将验证对象并取消装箱。

例如:

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

它还支持可空类型:

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

这可以简化从中提取数据的过程,DataTable因为无需显式地将对象转换或解析为正确的类型。


4

请考虑使用以下代码:

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

3

除非您有特定的理由来做ado.net,否则我将看一下使用ORM(对象关系映射器),例如nHibernate或LINQ to SQL。这样,您可以查询数据库并检索要使用的对象,这些对象具有强类型并且易于使用IMHO。


1
我得到ADO.net对移动到ORM之前的基本知识所建议stackoverflow.com/questions/1345508/...
RCIX

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

这个答案将受益于解释。从长远来看,纯代码答案很少有用。
TylerH's

-1

请注意,使用DataAdapter时不需要打开和关闭连接。

因此,我建议您更新此代码并删除连接的打开和关闭:

        SqlDataAdapter adapt = new SqlDataAdapter(cmd);

conn.Open(); //这行代码是不必要的

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

conn.Close(); //这行代码是不必要的

        Console.WriteLine("connection closed successfuly");

参考文件

本示例中显示的代码未明确打开和关闭Connection。如果Fill方法发现连接尚未打开,则隐式打开DataAdapter正在使用的Connection。如果“填充”打开了连接,则在“填充”完成时也会关闭连接。当您处理诸如填充或更新之类的单个操作时,这可以简化您的代码。但是,如果要执行多个需要打开连接的操作,则可以通过显式调用Connection的Open方法,对数据源执行操作,然后调用Connection的Close方法来提高应用程序的性能。您应该尝试尽可能短地保持与数据源的连接打开,以释放资源以供其他客户端应用程序使用。


这根本没有解决这个问题。
TylerH's
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.