簡體   English   中英

選擇表的列名和類型

[英]Select column names and types of a table

我正在寫一個訪問PostgreSQL數據庫的ac#程序。 由於我的程序應該可以通用運行,因此我需要動態獲取列名和相應的數據類型。

我的代碼如下所示:

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_創建93

C_HOMEPAGECONTENT 12

C_ID 12

列名正確,但是相應的數據類型以數字表示。 這些數字是一致的(12是字符串,-5長,93 DateTime)。

由於我都是C#和SQL的新手,所以我真的不知道錯誤的確切位置。 查詢是否已經錯誤或與C#中SQL數據類型的表示有關?

表格示例:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM