选择列的名称和类型

时间:2015-10-20 07:08:42

标签: c# postgresql

我正在编写一个访问PostgreSQL数据库的c#程序。 由于我的程序应该通用,我需要动态获取列名和相应的数据类型。

我的代码看起来像这样:

OdbcCommand command = new OdbcCommand("SELECT column_name, data_type FROM information_schema.columns", connection);
OdbcDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection);

using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\dummy5.txt"))
{
    while (reader.Read() == true)
    {                    
        s = reader.GetString(0) + "\t" + reader.GetString(1);
        file.Write(s + "\n");
    }                
}

结果我看起来像这样:

  

C_PK 12

     

C_URI 12

     

C_REV -5

     

C_CREATED 93

     

C_HOMEPAGECONTENT 12

     

C_ID 12

列名称正确但相应的数据类型表示为数字。这些数字是一致的(12是字符串,-5长,93 DateTime)。

由于我不熟悉C#和SQL,所以我真的不知道错误到底在哪里。查询是否已经错误或者是否与C#中SQL数据类型的表示有关?

1 个答案:

答案 0 :(得分:0)

示例表:

create table test (
    id serial primary key,
    str text not null,
    counter int default 0,
    val numeric);

使用pg_attribute

select
    attnum,
    attname, 
    format_type(atttypid, atttypmod) as atttype
from pg_attribute
where attrelid = 'test'::regclass
and attnum > 0 and not attisdropped
order by attnum;

 attnum | attname | atttype 
--------+---------+---------
      1 | id      | integer
      2 | str     | text
      3 | counter | integer
      4 | val     | numeric
(4 rows)

使用pg_attrdef获取默认表达式:

select
    attnum,
    attname, 
    format_type(atttypid, atttypmod) as atttype,
    pg_get_expr(adbin, adrelid) as defexpr,
    attnotnull
from pg_attribute
left join pg_attrdef
on adrelid = attrelid and adnum = attnum and atthasdef
where attrelid = 'test'::regclass
and attnum > 0 and not attisdropped
order by attnum;

 attnum | attname | atttype |             defexpr              | attnotnull 
--------+---------+---------+----------------------------------+------------
      1 | id      | integer | nextval('test_id_seq'::regclass) | t
      2 | str     | text    |                                  | t
      3 | counter | integer | 0                                | f
      4 | val     | numeric |                                  | f
(4 rows)