2015-11-07 89 views
-3

你好我有一個問題,得到「ExecuteNonQuery需要一個開放和可用的連接異常,連接的當前狀態是關閉的。」c#「ExecuteNonQuery需要一個開放且可用的連接,連接的當前狀態是關閉的。」

public void AddCustomer(Customer customer) 
    { 
     string connectionString = @"Data Source=LIRON-PC\SQLEXPRESS;Initial Catalog=C:\Program Files\Microsoft SQL Server\MSSQL12.SQLEXPRESS\MSSQL\DATA\MatokMmagnet.mdf;Integrated Security=True"; 
     using (m_sqlConnection = new SqlConnection(connectionString)) 
     { 
      m_cmd = new SqlCommand(); 
      m_cmd.CommandType = CommandType.Text; 
      m_cmd.Connection = m_sqlConnection; 

      m_cmd.Parameters.AddWithValue("@id", customer.id); 
      m_cmd.Parameters.AddWithValue("@FirstName", customer.FirstName); 
      m_cmd.Parameters.AddWithValue("@LastName", customer.LastName); 
      m_cmd.Parameters.AddWithValue("@Password", customer.Password); 
      m_cmd.CommandText = "INSERT INTO Customers (id, FirstName, LastName, Password)VALUES (@id, @FirstName, @LastName, @Password)"; 
      try 
      { 
       m_cmd.ExecuteNonQuery(); 
      } 
      catch(Exception e) 
      { 
       Console.WriteLine(e.Message); 
      } 
      finally 
      { 
       m_sqlConnection.Close(); 
      } 
     } 
    } 
+2

? – Steve

+0

你不打開連接並想執行查詢?在執行查詢之前打開它(m_sqlConnection.Open())。另外你還沒有關閉,因爲你使用了關閉連接的塊。 –

+0

您是否確定要將連接字符串嵌入代碼中。如果你需要改變它呢?你必須去很多地方去更新它。這不好! – mason

回答

2

像錯誤說,你必須打開執行這樣的查詢之前的連接:你不會從錯誤信息瞭解

public void AddCustomer(Customer customer) 
{ 
    string connectionString = @"Data Source=LIRON-PC\SQLEXPRESS;Initial Catalog=C:\Program Files\Microsoft SQL Server\MSSQL12.SQLEXPRESS\MSSQL\DATA\MatokMmagnet.mdf;Integrated Security=True"; 
    using (m_sqlConnection = new SqlConnection(connectionString)) 
    {` 
     m_sqlConnection.open(); 
     //.... 
    } 
} 
相關問題