0

我想从我的响应数据读取器对象中读取列名和类型,因为我需要它来实例化一些对象。我出来了:

using (db.sqlConnection) {
    db.sqlConnection.Open();
    using (var cmd = new SqlCommand("areaGetStreetTypes", db.sqlConnection)) {
        cmd.CommandType = CommandType.StoredProcedure;
        using (SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.KeyInfo)) {
            DataTable dt = dr.GetSchemaTable();
            foreach (DataRow myField in dt.Rows) {
                foreach (DataColumn coloana in dt.Columns) {
                    string c1 = coloana.ColumnName;  //column name ???
                    string c2 = coloana.GetType().ToString(); //column type ??
                    Console.WriteLine(c1 + "  " + c2);
                }
            }
        }
    }
}

但不工作。对于每一列返回我想打印(对于初学者)类似:

id_someID int32    
name string    
surname string     
ssn string

我的代码有什么问题?

4

3 回答 3

4

无需调用 GetSchemaTable 来获取每列的数据类型,因为 Reader 已经拥有所有这些详细信息

SqlCommand cmd = new SqlCommand(strSql, sqlConn);
SqlDataReader sdr;
sdr = cmd.ExecuteReader();
for (int i = 0; i < sdr.FieldCount; i++)
{
    string dataTypeName = sdr.GetDataTypeName(i); // Gets the type of the specified column in SQL Server data type format
    string FullName = sdr.GetFieldType(i).FullName; // Gets the type of the specified column in .NET data type format
    string specificfullname = sdr.GetProviderSpecificFieldType(i).FullName; //Gets the type of the specified column in provider-specific format
    //Now print the values
}   
于 2012-05-10T08:28:12.097 回答
3

我认为您实际上想要类似的东西

DataTable dt = dr.GetSchemaTable();
foreach (DataRow myField in dt.Rows) 
{
    var name = myField["ColumnName"];
    var type = myField["DataTypeName"];
    Console.WriteLine("{0} {1}", name, type);
}                     
于 2012-05-10T08:32:19.917 回答
1

使用DataColumn.DataType属性和CommandBehavior.SchemaOnly枚举成员。

于 2012-05-10T08:21:07.750 回答