简体   繁体   English

如何从C#中的select语句获取列名

[英]How can I get the column names from a select statement in c#

How can I access the column name of the field value inside the for loop. 如何在for循环中访问字段值的列名。

I don't want to have to hard code the column names. 我不想硬编码列名。

DataAccessObject NewDao = Settings.IntranetDBDataAccessObject;
string UserName = "";
string WorkPhone = "";
string ColumnName = "";

if (Request.QueryString["user_id"] != null && Request.QueryString["user_id"].Length != 0) {
     SqlCommand Select = new SqlCommand("SELECT emp_name, phone_work FROM employees WHERE emp_id="+ 
     NewDao.ToSql(Request.QueryString["user_id"].ToString(),FieldType.Integer),NewDao);

    DataRowCollection newDr = Select.Execute().Tables[0].Rows;

    for(int i = 0; i < newDr.Count; i++) {
       UserName = newDr[i]["emp_name"].ToString();
       WorkPhone = newDr[i]["phone_work"].ToString();

       //Is there a way to access the Key column that contains data row field value?
      //ColumnName = newDr[i][ ?columnNameFromSelect? ].ToString();
    }

    // Show a label value 
    UserInfo.Text =  UserName + ", phone: "+WorkPhone;
}

You should use the DataTable 's Columns property: 您应该使用DataTableColumns属性:

DataTable table = Select.Execute().Tables[0];
foreach (DataRow row in table.Rows)
{
    foreach (DataColumn col in table.Columns)
    {
        string colName = col.ColumnName;
        object value = row[col];
        // ...
    }
}

You can get the schema from your query also from the datareader : 您还可以从查询中从datareader获取模式:

SqlDataReader reader = command.ExecuteReader();
DataTable schemaTable = reader.GetSchemaTable();

as per documentation from msdn : https://msdn.microsoft.com/en-us/library/haa3afyz%28v=vs.110%29.aspx section about Getting Schema Information from the DataReader 根据msdn中的文档: https : //msdn.microsoft.com/en-us/library/haa3afyz%28v=vs.110%29.aspx部分,有关从DataReader获取架构信息

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

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