I’m working on a project that had a must-be-Postgres moment and before that I had worked with this database and C# once, in 2009. So, lots of thing changed since then.
Well, today I’m working with Npgsql…
“Npgsql is a .Net Data Provider for Postgresql. It allows any program developed for .Net framework to access database server. It is implemented in 100% C# code. Works with Postgresql 7.x and above.”
All right, there’s a great and complete documentation at Npgsql’s website and I hardly recommend that you take a look at them. Cause I’m here just to make it quickly, a full tutorial that will approach you to the main 4 actions that you use while working with database
Insert
Delete
Update
Query
Before everything, make sure you have downloaded Npgsql’s dll (which you can find here). Don’t forget to add it as a Reference.
I’ll try to write a generic database class, very simple one with the main methods using Reflection (which, in case you don’t know what’s that, take a look at MSDN, it’s just awesome!). This way, you will be able to use the same class in different projects, sometimes you will need to ajust only a couple of lines of code.
Here we go…
We will need a variable which will connect direct to the database and call us the methods we want, remember to configure it with your database server, port, user and password.
Before we start calling our methods, it is important to between every operation follow this instruction:
Open connection
Do your stuff
Close connection
This will prevent you to get in trouble. So, here it is our Open and Close connection.
Ok so, let’s get it started by Insert operations. All you are going to need as parameter is the table name.
The update method goes below.
Pay attention to this code, I will assume that my table has an integer id as primary key. (Remember that I told you about few adjustments? Here it is!)
The delete method follows the same path as the update part. An integer id as primary key.
To make it simpler and (bad looking), I have splitted the Query method in two, the first one will get all data from your table and the second allows you to use parameters in your SQL query string.
Querying everything…
Querying only what you really want…
Thats pretty much it! Before I forget, I want to focus on two things.
This is working for only one table. It’s just a simple example. If you want to do your nested queries, it’s all about the SQL string builder.
When you query into your database and get a List