如何使用SqlDataReader获取列的DataType和Size?

我试图获取给出的每个列的数据类型进行一些validation我已经尝试了getSchemaTable但它只给了我一个没有值的表的模式。

例如,我的数据库中有一个表和一个列名: id_declarant 。 我想从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); 

 Type type = reader.GetFieldType(0); 

请使用函数GetTableSchema。

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

使用表模式,您可以使用c#获取所有与列相关的属性。

谢谢 。

您可以使用GetDataTypeName()函数来获取字段的数据类型

  String dataType = reader.GetDataTypeName(FIELD_INDEX); 
 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; }