Articles → .NET → CRUD operations in postgres using C#

CRUD operations in postgres using C#










Import SQLite libraries









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