dir.by  
Поиск >>

Компьютер, программы
→
PostgreSQL server (database) and pgAdmin (program for working with PostgreSQL server). Works on different platforms: Unix, Windows
 Создаем C# консольное приложение для соединение с сервером PostgreSQL и пишем SQL запрос для получения данных. Данные получаем в виде json 
посмотрели 10591 раз
обновлено: 22 September 2021
Шаг 1. Создаем C# приложение
Шаг 2. Добавим nuget package "npgsql"
Шаг 3. Добавим nuget package "Newtonsoft.json" для конвертации текста в формате json в C# класс
Шаг 4. Добавим код для соединения с сервером PostgreSQL и SQL запрос для получения данных
  C#     Добавим код в файл Program.cs
using Newtonsoft.Json;
using Npgsql;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
     static class UtilsPostgres
     {
          public static NpgsqlConnection Connect(string connectionString)
          {
               NpgsqlConnection conn = new NpgsqlConnection(connectionString);
               try
               {
                    conn.Open();
               }
               catch (Exception e)
               {
                    throw new Exception("Error connecting to the database", e);
               }
               return conn;
          }

          public static async Task ExecuteSelectAsJson(NpgsqlConnection conn, string sql, Action<string> callback)
          {
               try
               {
                    using (var command = conn.CreateCommand())
                    {
                         command.CommandText = sql;
                         var result = await command.ExecuteScalarAsync();
                         if (result is string json)
                         {
                              callback(json);
                         }
                    }
               }
               catch (Exception e)
               {
               }
          }
     }

     public class City
     {
          public int CityId { get; set; }
          public string CityName { get; set; }
     }

     class Program
     {
          static async Task Main(string[] args)
          {
               // connect
               string connectionString = "Server=localhost; Port=5432; Database=postgres; UserId=postgres; Password=evgen12345; commandTimeout=120;";
               var conn = UtilsPostgres.Connect(connectionString);

               // getting data
               string sql = $@"
                                   SELECT json_agg(row_to_json(cities))
                                   FROM
                                   (
                                        SELECT
                                             id AS CityId,
                                             name AS CityName
                                        FROM city
                                   ) AS cities;
                              "
;
               await UtilsPostgres.ExecuteSelectAsJson(conn, sql, json => {

                    // show json
                    Console.WriteLine(json);

                    // convert json to list
                    var cities = JsonConvert.DeserializeObject<List<City>>(json);

                    // show list
                    foreach (var item in cities)
                    {
                         Console.WriteLine($"{item.CityId} {item.CityName}");
                    }

               });

               Console.ReadLine();
          }
     }
}
Запустим программу и увидим результат
На заметку! Параметры для соединения с сервером PostgreSQL
string connectionString = "Server=localhost; Port=5432; Database=postgres; UserId=postgres; Password=evgen12345; commandTimeout=120;";
Параметры берутся вот здесь:

Открываем pgAdmin
Если иконки pgAdmin нет на рабочем столе в Windows тогда создадим:
 
Открывается pgAdmin
 
Вводим пароль который создали при установке PostgreSQL сервера (база данных) ...
 
Откроется pgAdmin и мы увидим сервер:
Еще! Расширяем sql чтобы в json брать данные из таблицы "person" и связанной таблицы "city"
  C#     Добавим код в файл Program.cs
using Newtonsoft.Json;
using Npgsql;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
     static class UtilsPostgres
     {
          public static NpgsqlConnection Connect(string connectionString)
          {
               NpgsqlConnection conn = new NpgsqlConnection(connectionString);
               try
               {
                    conn.Open();
               }
               catch (Exception e)
               {
                    throw new Exception("Error connecting to the database", e);
               }
               return conn;
          }

          public static async Task ExecuteSelectAsJson(NpgsqlConnection conn, string sql, Action<string> callback)
          {
               try
               {
                    using (var command = conn.CreateCommand())
                    {
                         command.CommandText = sql;
                         var result = await command.ExecuteScalarAsync();
                         if (result is string json)
                         {
                              callback(json);
                         }
                    }
               }
               catch (Exception e)
               {
               }
          }
     }

     public class Person
     {
          public int PersonId { get; set; }
          public string FirstName { get; set; }
          public string LastName { get; set; }
     }


     public class City
     {
          public int CityId { get; set; }
          public string CityName { get; set; }
          public List<Person> Persons { get; set; }
     }

     class Program
     {
          static async Task Main(string[] args)
          {
               // connect
               string connectionString = "Server=localhost; Port=5432; Database=postgres; UserId=postgres; Password=evgen12345; commandTimeout=120;";
               var conn = UtilsPostgres.Connect(connectionString);

               // getting data
               string sql = $@"
                                   SELECT json_agg(row_to_json(aaa))
                                   FROM
                                   (
                                        SELECT
                                             id AS CityId,
                                             name AS CityName,
                                             (
                                                  SELECT json_agg(row_to_json(bbb))
                                                  FROM
                                                  (
                                                       SELECT
                                                            id AS PersonId,
                                                            first_name AS FirstName,
                                                            last_name AS LastName
                                                       FROM person
                                                       WHERE person.city_id=city.id
                                                  ) AS bbb
                                             ) AS Persons

                                        FROM city
                                   ) AS aaa;
                              "
;
               await UtilsPostgres.ExecuteSelectAsJson(conn, sql, json => {

                    // show json
                    Console.WriteLine(json);

                    // convert jsobn to list
                    var cities = JsonConvert.DeserializeObject<List<City>>(json);

                    // show list
                    foreach (var item in cities)
                    {
                         Console.WriteLine($"{item.CityId} {item.CityName}");
                    }

               });

               Console.ReadLine();
          }
     }
}
 
← Previous topic
Create a C# console application to connect to the PostgreSQL server and write an SQL query to get the data
 
Next topic →
Add auto increment when the column is already created (PostgreSQL queries)
 
Your feedback ... Comments ...
   
Your Name
Your comment (www links can only be added by a logged-in user)

Новость "Черная пятница" Dreame в Беларуси – две недели скидок до 3400 рублей
 
PostgreSQL server
• What is a PostgreSQL server database?
• Download and install a PostgreSQL server (database) on Windows
pgAdmin program for working with PostgreSQL server (working on Windows)
• Download and install pgAdmin (a program for working with PostgreSQL) | Windows
• Open pgAdmin and connect to a remote PostgreSQL server
• Open pgAdmin and write an SQL query to fetch data from the PostgreSQL server
Creating tables
• Create the "city" table (using pgAdmin, PostgreSQL server)
• Create the "person" table and link it to the "city" table (using pgAdmin, a PostgreSQL server)
Adding data to tables
• Add data to the "city" table (using pgAdmin, PostgreSQL server)
• Add data to the "person" table (using pgAdmin, PostgreSQL server)
C# data retrieval application
• Create a C# console application to connect to the PostgreSQL server and write an SQL query to get the data
• Create a C# console application to connect to the PostgreSQL server and write an SQL query to get the data. We receive the data in the form of json
PostgreSQL queries
• Add auto increment when the column is already created (PostgreSQL queries)
• Changing the column type from boolean to bit(1) | PostgreSQL queries
• Changing the column type from bit(1) to boolean | PostgreSQL queries

  Ваши вопросы присылайте по почте: info@dir.by