2012-09-16 62 views
0

我是一個簡單的數據庫項目的工作在C尖銳和MS SQL服務器2008年,但在編譯程序有錯誤IM的SQL Server的坡平了此消息:異常連接到從C#

的類型初始值對於 'StudentsInformationSystem.DB_conection' 拋出一個異常

我的代碼:拋開

namespace StudentsInformationSystem 
{ 
    class DB_Access 
    { 
     private SqlConnection conn; 

     public DB_Access() 
     { 
      conn = DB_conection.GetConnection(); //this is where i am getting the error on this line of code 

     } 

     public void add_student(string regNo,string fname, string lname, string phoneNo) 
     { 
      if (conn.State.ToString() == "closed") 
      { 
       conn.Open(); 
      } 

      SqlCommand newCmd = conn.CreateCommand(); 
      newCmd.Connection = conn; 
      newCmd.CommandType = CommandType.Text; 
      newCmd.CommandText = "insert into student values('" + regNo + "','" + fname + "','" + lname + "','" + phoneNo + "')"; 
      newCmd.ExecuteNonQuery(); 
     } 
    } 
} 
+4

這不是一個編譯器錯誤。閱讀InnerException。 – SLaks

+0

即時新手介意向我解釋你的意思嗎?就像InnerException一樣。 –

+0

你會得到什麼錯誤?請告訴錯誤句子。很可能它會像「連接不開放」這樣嗎? – Sami

回答

3

SQL注入的問題,你的問題likel y來自比較ConnectionState到一個字符串。

/* this will never be true because "closed" is not equal to "Closed" */ 
if (conn.State.ToString() == "closed") 
{ 
    conn.Open(); 
} 

...應該是:

if (conn.State == ConnectionState.Closed) 
{ 
    conn.Open(); 
} 

你也應該得到連接,接近其使用盡可能和從未其存儲爲類級變量。

using (var conn = DB_conection.GetConnection()) 
using (var cmd = conn.CreateCommand()) 
{ 
    // use conn & cmd 

    // they will be closed & disposed of when they leave this block 
} 
+0

它仍然給我同樣的問題,我已經編輯它,告訴你在哪裏得到錯誤 –

+0

@MildredShimz:我的答案仍然有效,你會遇到的其他問題。爲了充分回答你的問題,你需要發佈'DB_connection'的代碼。 –

+0

至於實際上有'DB_connection'類,請參閱此答案:http://stackoverflow.com/a/9707060/4068 –

1

假設有一個與你的DB_conection(你有沒有共享它的細節)

很少的代碼改進沒有問題

public void add_student(string regNo,string fname, string lname, string phoneNo) 
{ 
    if (conn.State == ConnectionSate.Closed)   
      conn.Open();   
    SqlCommand newCmd = conn.CreateCommand(); 
    newCmd.CommandText = "insert into student values('" + regNo + "','" + fname + "','" + lname + "','" + phoneNo + "')"; 
    newCmd.ExecuteNonQuery(); 
} 

我會建議不要關閉每個連接後查詢爲了快速訪問數據庫,並且您已經在執行此操作。但是,在使用數據讀取器之後,應該關閉數據讀取器,否則可能會導致一些錯誤

//newCmd.Connection = conn;沒有必要在上面的語句中做到這一點

//newCmd.CommandType = CommandType.Text;沒有必要,這是默認情況

0

Type initializer for [class name] threw an exception.

這表明一個類的靜態構造函數中引發異常。您需要檢查類DB_conection的靜態構造函數。其代碼將在靜態方法調用GetConnection之前的代碼中執行。

如果你在調試器中運行你的代碼,我相信異常的來源是顯而易見的。