编程语言
首页 > 编程语言> > c# – 我们如何从getschemaTable获取Column Size和dataType?

c# – 我们如何从getschemaTable获取Column Size和dataType?

作者:互联网

我是一个新手,我正在尝试从我的数据库中的某些表中检索列NAme,大小(最大legth)和DataType,当我执行它时,以下代码期望它显示所有列类型和名称(我没有找到如何引用Size,我使用了ColumnSize,但据说DataColumn不包含此方法的定义)
但在执行时,它只显示:IsColumnSetSystem.Boolean
这是代码:

private void button1_Click(object sender, EventArgs e)
    {
        string EF = textBox1.Text;

        try{
            //SqlDataAdapter adapter = SetupDataAdapter("SELECT * FROM id_declarant");
     SqlCommand comm = new SqlCommand();
     string connectionString = @"Data Source=.\SQLEXPRESS;Initial Catalog=declaration;Integrated Security=True";
      comm.Connection=new SqlConnection(connectionString);
            String sql = @"SELECT * 
                  FROM id_declarant,declarant
                 WHERE (declarant.Nom_pren_RS='" + EF + "') and (id_declarant.mat_fisc=declarant.mat_fisc)  "; 
     comm.CommandText = sql;
  comm.Connection.Open();
             SqlDataReader reader = comm.ExecuteReader();
             DataTable schemaTable = reader.GetSchemaTable();
             foreach (DataRow row in schemaTable.Rows)
             {
                 foreach (DataColumn column in schemaTable.Columns)
                 {
                     System.IO.File.WriteAllText(@"C:\Users\Manuela\Documents\GL4\WriteLines.txt", column.ColumnName + column.DataType );

                 }
             }

解决方法:

您正在打印由GetSchemaTable返回的数据表的列名,而不是其值,我建议使用StringBuilder并在退出循环时写入所有内容

    StringBuilder sb = new StringBuilder();
    foreach (DataRow row in schemaTable.Rows)
    {
        foreach (DataColumn column in schemaTable.Columns)
        {
            sb.AppendLine(column.ColumnName + ":"  +row[column.ColumnName].ToString());
        }
        sb.AppendLine();
    }
    File.WriteAllText(@"C:\Users\Manuela\Documents\GL4\WriteLines.txt", sb.ToString());

标签:c,database,net,datareader,getschematable
来源: https://codeday.me/bug/20190715/1468262.html