Working with PostgreSQL in C#
Not long ago, I started developing an application on C# based on PostgreSQL, and I'd like to share the information I've found. In this article, I'll describe what you need to connect to PostgreSQL from an application written in C#, and how to work with it using examples.
To be able to work with PostgreSQL databases in our case, we will use Npgsql — .Net Data Provider for Postgresql download, add Npgsql.dll to your project, and copy the necessary libraries (to work): Npgsql.dll and Mono.Security.dll.
Let's start with the connection to the database:
string conn_param = "Строка подключения к базе"; //Например: "Server=127.0.0.1;Port=5432;User Id=postgres;Password=mypass;Database=mybase;"
string sql = "текст запроса к базе данных";
NpgsqlConnection conn = new NpgsqlConnection(MainParams.ConnectionString);
NpgsqlCommand comm = new NpgsqlCommand(sql, conn);
conn.Open(); //Открываем соединение.
result = comm.ExecuteScalar().ToString(); //Выполняем нашу команду.
conn.Close(); //Закрываем соединение.
As you can see, nothing complicated, everything as usual.
comm.ExecuteScalar() — returns a value.
comm.ExecuteNonQuery() — executes a query to modify data.
Example of selecting an array of data:
NpgsqlConnection con = new NpgsqlConnection("строка подключения");
NpgsqlCommand com = new NpgsqlCommand("select * from my_table order by \\"NAME\\"", con);
con.Open();
NpgsqlDataReader reader;
reader = com.ExecuteReader();
while (reader.Read())
{
try
{
string result = reader.GetString(1);//Получаем значение из второго столбца! Первый это (0)!
}
catch { }
}
con.Close();
That's all the most important, in my opinion.
Comments (0)
No comments yet.