Articles → .NET → CRUD Operations In Postgres Using C#

CRUD Operations In Postgres Using C#





  1. Get data from postgresql table.
  2. Insert/update/delete in postgresql tables.

Import Sqlite Libraries




  1. mono.security.dll
  2. npgsql.dll

Connectionstring For Postgresql


public string ConnectionString {
  get {
    return@"Provider=PostgreSQL OLE DB Provider;Server=127.0.0.1;
Database=<db_name>;User ID=<user_name>;password=<password>;";
  }
}



Method To Get Data From Table


public DataTable GetResultSetTable(string query) {
  DataTable table = new DataTable();
  using(NpgsqlConnection connection = new NpgsqlConnection(ConnectionString)) {
    connection.Open();
    using(NpgsqlCommand command = new NpgsqlCommand(query, connection)) {
      using(NpgsqlDataAdapter adapter = new NpgsqlDataAdapter()) {
        adapter.SelectCommand = command;
        adapter.Fill(table);
      }
    }
  }
  return table;
}



Method To Perform Insert/Update/Delete Operation In The Table


public void ExecuteQuery(string query) {
  using(NpgsqlConnection connection = new NpgsqlConnection(ConnectionString)) {
    connection.Open();
    using(NpgsqlCommand command = new NpgsqlCommand(query, connection)) {
      command.ExecuteNonQuery();
    }
  }
}



Download



Posted By  -  Karan Gupta
 
Posted On  -  Wednesday, October 23, 2019

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250