C#連接Postgresql 需要額外的Npgsql 幫忙。以下是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 9.x and above.
中文翻譯如下(小弟自翻):
Npgsql是一個.Net的Postgresql資料供應器。它充許任何以.NET Framework開發的程式來存取Postgresql資料庫系統。它的原始碼100%由C#實作。支援PostgreSQL 9.x以上的版本。
一、首先請到官網下載Npgsql,但請注意您所運作的.NET Framework 版本。如下所示
net20 表示.NET Framework 2.0 ,
net35表示.NET Framework 3.5
net40表示 .NET Framework 4.0
net45表示.NET Framework 4.5
如果不確定目標Framework.可以用此方式查看,首先在Properties 點二下。
接下來會出現以下畫面,注意目標Framework的地方。
二、解壓縮zip (在本篇我選用4.0)
三、在Visual Studio中加入參考
左邊選擇瀏覽
點擇下圖中的二個檔案即可。
成功參考後會出現剛才加入的二個dll檔案。

四、連接範例程式碼如下
首先要記得Using Npgsql的東西進來
using Npgsql;接下來說明連接字串所表示的意義
Server=您的IP;Port=5432;User Id=使用者名稱;Password=使用者密碼;Database=要連接的資料庫;最後是完整的程式碼─讀取Demo資料庫中的shop_sale資料表。
NpgsqlConnection conn =
new NpgsqlConnection("Server=127.0.0.1;Port=5432;User Id=user;Password=1234;Database=Demo;");
conn.Open();
NpgsqlCommand command =
new NpgsqlCommand("select * from shop_sale", conn);
try
{
NpgsqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
string shop = reader["shop"].ToString(); ;
string no = reader["no"].ToString(); ;
Console.WriteLine(shop + "\t" + no);
}
}
finally
{
conn.Close();
}
想知道更詳細的內容,請參考這個網址






沒有留言:
張貼留言