2013-06-24 2 views
4

일부 확인을 위해 주어진 각 열의 데이터 형식을 얻으려고합니다. 이미 getSchemaTable을 시도했지만 값이없는 테이블의 스키마 만 제공합니다.SqlDataReader를 사용하여 열의 데이터 형식 및 크기를 얻는 방법?

예를 들어, 데이터베이스에 테이블이 있고 열 이름이 id_declarant입니다. 데이터 유형 및 값의 크기를 id_declarant에서 검색하고 싶습니다.

comm.Connection=new SqlConnection(connectionString); 
String sql = @" 
      SELECT * 
      FROM id_declarant,declarant 
      WHERE (declarant.Nom_pren_RS='" + textBox1.Text + "') 
      and (id_declarant.mat_fisc=declarant.mat_fisc) "; 
comm.CommandText = sql; 
comm.Connection.Open(); 
string mat_fisc; 
string clé_mat_fisc; 
string categorie ; 
string num_etab_sec ; 
string activite; 
StringBuilder sb = new StringBuilder(); 
String Nom = textBox1.Text; 
using (SqlDataReader reader = comm.ExecuteReader()) 
{ 
    while (reader.Read()) 
    { 
     //here i want to know how to retrieve the reader[0].Type and Size to do the verification 
     mat_fisc = reader[0].ToString(); 
     clé_mat_fisc = reader["clé_mat_fisc"].ToString(); 
     categorie = reader["categorie"].ToString(); 
     num_etab_sec = reader["num_etab_sec"].ToString(); 
     activite = reader["activite"].ToString(); 
     sb.Append("EF" + mat_fisc + clé_mat_fisc + categorie + num_etab_sec + textBox2.Text + textBox3.Text + Nom + activite); 

답변

3
Type type = reader.GetFieldType(0); 
+1

답변을 자세히 설명해 주시겠습니까? – Stephan

+0

나는 이것을 시도했다 : string Type = reader [ "id_declarant"]. GetFieldType (0) .FullName; 하지만 System.string을 표시합니다. – manu

+0

유형 type = reader.GetFieldType (0); 문자열 대신 Type = reader [ "id_declarant"]. GetFieldType (0) .FullName; BTW, id_declarant의 데이터 유형은 무엇입니까? – ojlovecd

0

당신은

String dataType = reader.GetDataTypeName(FIELD_INDEX); 
0
public string ReadString(IDataReader reader, string columnName) { 

string myString = ""; 

var index = reader.GetOrdinal(columnName); 

var fieldType = reader.GetFieldType(index); 

if (fieldType.FullName.Contains("Guid")) 
{ 
myString = reader.IsDBNull(index) ? "" : reader.GetGuid(index).ToString(); 
} 
else 
{ 
myString = reader.IsDBNull(index) ? "" : reader.GetString(index); 
} 
return myString; 
} 
0

이 기능 GetTableSchema를 사용하십시오 필드의 데이터 형식을 얻을 수 GetDataTypeName() 함수를 사용할 수 있습니다 여기에

는 코드입니다.

SqlDataReader reader= command.ExecuteReader(); 

using (var schemaTable = reader.GetSchemaTable()) 
    { 
     foreach (DataRow row in schemaTable.Rows) 
     { 
      string ColumnName= row.Field<string>("ColumnName"); 
      string DataTypeName= row.Field<string>("DataTypeName"); 
      short NumericPrecision= row.Field<short>("NumericPrecision"); 
      short NumericScale= row.Field<short>("NumericScale"); 
      int ColumnSize= row.Field<int>("ColumnSize"); 
      Console.WriteLine("Column: {0} Type: {1} Precision: {2} Scale: {3} ColumnSize {4}",  
      ColumnName, DataTypeName, NumericPrecision, scale,ColumnSize); 
     } 
    } 

테이블 스키마를 사용하면 C#을 사용하여 모든 열 관련 속성을 가져올 수 있습니다.

감사합니다.

관련 문제