你好我遇到了#34的异常问题; 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();
}
}
}
答案 0 :(得分: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();
//....
}
}