Reputation: 35
I have a table in my database consisting of one column which is NewLanguage(varchar).I insert new languages to the table and i want to select the rows of the table and assign them to a string variable splitted by ','. I try to select the languages as in the code.
public string SelectLanguagesFromDatabase()
{
NpgsqlCommand COM = new NpgsqlCommand(null,dbConnection);
COM.CommandText = "select * from \"Languages\"";
}
How can I select roes from database and assign them to string variable?
In an example
if Languages Column is
NewLanguage
C
c++
java
I want to have a a string as "C,c++,java". How can I do that ? Thanks.
Upvotes: 0
Views: 280
Reputation: 87074
Adapted from the user manual and using Ilesh Patel's query:
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();
}
}
}
Upvotes: 0
Reputation: 2155
You can use string_agg to concatenate all values from particular column in comma separated text like below:
SELECT string_agg (NewLanguage,',') FROM "Languages"
Upvotes: 2