2012-08-07 84 views
2

這是我第一次連接到數據庫,但我有一些問題C#連接到Postgres數據庫

using Npgsql; 

namespace DBPrj 
{ 
class Program 
{ 
    static void Main(string[] args) 
    { 
     bool boolfound=false; 
     NpgsqlConnection conn = new NpgsqlConnection("Server=<ip>; Port=5432; User Id=Admin; Password=postgres.1; Database=Test1"); //<ip> is an actual ip address 
     conn.Open(); 

     NpgsqlCommand cmd = new NpgsqlCommand(); 
     NpgsqlDataReader dr= cmd.ExecuteReader(); //I get InvalidOperationException : The connection is not open. 
     if (dr.Read()) 
     { 
      boolfound=true; 
      Console.WriteLine("connection established"); 
     } 
     if(boolfound==false) 
     { 
      Console.WriteLine("Data does not exist"); 
     } 
     dr.Close(); 
     conn.Close(); 



    } 
} 

}

可能是什麼問題呢? NpgsqlConnection字符串是否正確寫入?數據庫可以被遠程訪問保護嗎?

我該如何解決這個問題?

在此先感謝!

回答

4

你永遠不分配您NpgsqlConnectionNpgsqlCommand,你不提供查詢爲您NpgsqlDataReader,應解燃眉之急固定執行。

另外,至少要將NpgsqlConnection包裝在using()中,最好確保連接總是關閉,即使存在異常也是如此。

using Npgsql; 

namespace DBPrj 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      bool boolfound=false; 
      using(NpgsqlConnection conn = new NpgsqlConnection("Server=<ip>; Port=5432; User Id=Admin; Password=postgres.1; Database=Test1")) 
      { 
       conn.Open(); 

       NpgsqlCommand cmd = new NpgsqlCommand("SELECT * FROM Table1", conn); 
       NpgsqlDataReader dr= cmd.ExecuteReader(); 
       if (dr.Read()) 
       { 
        boolfound=true; 
        Console.WriteLine("connection established"); 
       } 
       if(boolfound==false) 
       { 
        Console.WriteLine("Data does not exist"); 
       } 
       dr.Close(); 
      } 
     } 
    } 
} 
+0

我的懷疑是正確的,關於命令的重載。 – 2012-08-07 10:33:57

1

在您的連接字符串中,您可能會在數據庫末尾缺少分號。

Database=Test1" 

可能需要;

Database=Test1;" 

也 - 這可能是值得在用戶友好和易於捕捉錯誤的嘗試catch語句包裹你的conn.open()。

編輯1:

只是做了一點點閱讀。 NpgsqlCommand是否需要將參數傳遞給它?只是在僞代碼中,類似於;

NpgsqlCommand cmd = new NpgsqlCommand(query, conn); 
+0

仍然是同樣的問題,雖然 – robertpas 2012-08-07 10:18:18

+0

看到我的編輯,thx的幫助可能是這樣的。 – 2012-08-07 10:30:01