在C#中获取postgres表数据(CSV格式)

时间:2017-05-24 08:24:03

标签: c# postgresql

CSV获取查询:

COPY (select * from a.table) TO STDOUT WITH CSV DELIMITER ';' HEADER

如果使用 command.ExecuteReader()尝试收到错误,如何在C#中获取查询数据:

System.Exception: Received unexpected backend message CopyOutResponse. Please file a bug.

1 个答案:

答案 0 :(得分:0)

你总是可以强行执行任务......

    private const string QUOTE = "\"";
    private const string ESCAPED_QUOTE = "\"\"";
    private static char[] CHARACTERS_THAT_MUST_BE_QUOTED = { ',', '"', '\n', '\r' };

    private static string Escape(string s)
    {
        if (string.IsNullOrEmpty(s))
            return string.Empty;

        if (s.Contains(QUOTE))
            s = s.Replace(QUOTE, ESCAPED_QUOTE);

        if (s.IndexOfAny(CHARACTERS_THAT_MUST_BE_QUOTED) > -1)
            s = QUOTE + s + QUOTE;

        return s;
    }

    private void SqlToFile(string Sql, string FileName)
    {
        NpgsqlCommand cmd = new NpgsqlCommand(Sql, conn);
        NpgsqlDataReader reader = cmd.ExecuteReader();

        string[] outline = new string[reader.FieldCount];

        StreamWriter sw = new StreamWriter(FileName);

        while (reader.Read())
        {
            while (reader.Read())
            {
                for (int i = 0; i < reader.FieldCount; i++)
                    outline[i] = Escape(reader.GetValue(i).ToString());

                sw.WriteLine(String.Join(",", outline));
            }

        }

        reader.Close();
        sw.Close();
    }

Escape方法的欠款,虽然我不记得是谁偷了它。