从datareader加载数据

时间:2012-05-10 08:16:22

标签: c# .net ado.net database-schema

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

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

我的代码有什么问题?

3 个答案:

答案 0 :(得分: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
}   

答案 1 :(得分: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);
}                     

答案 2 :(得分:1)

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