Postgres - 在查询中恢复列名的优雅方式

时间:2011-12-14 04:41:47

标签: c# postgresql

将一个超级简单的查询工具放在一起如下所示:

enter image description here

问题:如何让列名通过,以便它们与查询结果匹配?

代码是

 NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;Port=5432;User Id=postgres;Password=letmein;Database=dave;");
        conn.Open();

        try {
            var colName = new NpgsqlCommand(@"SELECT column_name
                                            FROM information_schema.columns
                                            WHERE table_schema='public' AND table_name='simple_table' ORDER BY column_name", conn);

            NpgsqlDataReader dr = colName.ExecuteReader();

            while (dr.Read()) {
                for (int i = 0; i < dr.FieldCount; i++) 
                    txtResults.Text += dr[i] + " ";
            }
            txtResults.Text += "\r\n \r\n";

            var command = new NpgsqlCommand(txtSql.Text, conn);
            dr = command.ExecuteReader();

            while (dr.Read()) {
                for (int i = 0; i < dr.FieldCount; i++) 
                    txtResults.Text += dr[i] + "  ";
                txtResults.Text += "\r\n";
            }
        }
        finally {
            conn.Close();
        }

3 个答案:

答案 0 :(得分:1)

表示参考:

 for (int i = 0; i < dr.FieldCount; i++)
 {
    fieldnames += dr.GetName(i) + " | " ;
 }

或这是正在运行的代码:

            DataSet dset = new DataSet("npdata");
            NpgsqlDataAdapter NpAdapter = new NpgsqlDataAdapter();
            NpAdapter.SelectCommand = new NpgsqlCommand(sql, conn);
            NpAdapter.Fill(dset, "npdata");
            var dtsource = dset.Tables["npdata"];
            dataGridView.DataSource = dtsource;
            dataGridView.DataBind();

答案 1 :(得分:0)

您可以使用DataGrid显示结果:

        DataTable dt = new DataTable();
        dt.Load(reader);
        dataGridView1.DataSource = dt;

答案 2 :(得分:0)

在控制台中检索所有columnName:fieldValue:

            for(int i=0; i < ds.Tables[0].Rows.Count; i++)
                for(int j=0; j < ds.Tables[0].Rows[i].ItemArray.Length; j++)
                    Console.WriteLine(ds.Tables[0].Columns[j].ToString() + " : " + ds.Tables[0].Rows[i][j].ToString());