dir.by  
Поиск >>

Компьютер, программы
→
PostgreSQL server (database) and pgAdmin (program for working with PostgreSQL server). Works on different platforms: Unix, Windows
 Создаем C# консольное приложение для соединение с сервером PostgreSQL и пишем SQL запрос для получения данных 
посмотрели 6587 раз
обновлено: 18 September 2021
Шаг 1. Создаем C# приложение
Шаг 2. Добавим nuget package "npgsql"
Шаг 3. Добавим код для соединения с сервером PostgreSQL и SQL запрос для получения данных
  C#     Добавим код в файл Program.cs
using Npgsql;
using System;
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 ExecuteSelectAsReader(NpgsqlConnection conn, string sql, Action<NpgsqlDataReader> callback)
          {
               using (var command = conn.CreateCommand())
               {
                    command.CommandText = sql;
                    using (var reader = await command.ExecuteReaderAsync())
                    {
                         callback(reader);
                    }
               }
          }
     }

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

               // getting data
               string sql = "SELECT id, name FROM city";
               await UtilsPostgres.ExecuteSelectAsReader(conn, sql, reader => {
                    while (reader.Read())
                    {
                         var id = reader.GetInt32(0);
                         var name = reader.GetString(1);
                         Console.WriteLine($"{id} {name}");
                    }
               });

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

Открываем pgAdmin
Если иконки pgAdmin нет на рабочем столе в Windows тогда создадим:
 
Открывается pgAdmin
 
Вводим пароль который создали при установке PostgreSQL сервера (база данных) ...
 
Откроется pgAdmin и мы увидим сервер:
На заметку! Данные для базы данных PostgreSQL добавили вот
 
← Previous topic
Add data to the "person" table (using pgAdmin, PostgreSQL server)
 
Next topic →
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
 
Your feedback ... Comments ...
   
Your Name
Your comment (www links can only be added by a logged-in user)

Новость "Черная пятница" на технику Dreame в Беларуси с 17 по 30 ноября 2026 года – две недели скидок до 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