Articles → CSHARP → CRUD Operations In Postgres Using C#
CRUD Operations In Postgres Using C#
- Get data from postgresql table.
- Insert/update/delete in postgresql tables.
Import Sqlite Libraries
- mono.security.dll
- 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