簡體   English   中英

從數據庫中讀取行,並將行值分配給Postgresql和C#中的字符串變量

[英]Read rows in from database and assign the rows values to a string variable in Postgresql and C#

我的數據庫中有一個表,其中一列是NewLanguage(varchar)。我向表中插入新語言,我想選擇表中的行並將其分配給以','分隔的字符串變量。 我嘗試選擇代碼中的語言。

public string  SelectLanguagesFromDatabase()
    {

        NpgsqlCommand COM = new NpgsqlCommand(null,dbConnection);
        COM.CommandText = "select * from \"Languages\"";


    }

如何從數據庫中選擇魚卵並將其分配給字符串變量?

In an example

如果語言列為

  NewLanguage

 C
 c++
 java

我想要一個字符串作為“ C,c ++,java”。 我怎樣才能做到這一點 ? 謝謝。

您可以使用string_agg連接來自逗號分隔的文本中特定列的所有值,如下所示:

SELECT string_agg (NewLanguage,',') FROM "Languages"

根據用戶手冊改編並使用Ilesh Patel的查詢:

using System;
using System.Data;
using Npgsql;

public static class NpgsqlUserManual
{
  public static void Main(String[] args)
  {
    NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;Port=5432;User Id=joe;Password=secret;Database=joedata;");
    conn.Open();

    NpgsqlCommand command = new NpgsqlCommand("SELECT string_agg(NewLanguage,',') FROM Languages", conn);
    String results;

    try
    {
      results = (String)command.ExecuteScalar();
      Console.WriteLine("{0}", results);
    }


    finally
    {
      conn.Close();
    }
  }
}

暫無
暫無

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

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