我遇到了这个小问题:每次我的代码执行下面的 InsertOrder() 例程时,我都会收到此异常消息:“连接字符串尚未启动”。
这是 InsertOrder() 方法的代码:
private void InsertOrder()
{
string insertSQL = "";
insertSQL += "INSERT INTO Orders (";
insertSQL += "UserName, DateCreated, LastUpdate, Description, PaymentType, Delivery, Total) ";
insertSQL += "VALUES (@UserName, @DateCreated, @LastUpdate, @Description, @PaymentType, @Delivery, @Total)";
SqlCommand cmd0 = new SqlCommand(insertSQL, connection);
// Adds the parameters
cmd0.Parameters.AddWithValue("@UserName", Profile.UserName.ToString());
cmd0.Parameters.AddWithValue("@DateCreated", Profile.Orders.SCart.DateCreated());
cmd0.Parameters.AddWithValue("@LastUpdate", Profile.Orders.SCart.LastUpdate());
cmd0.Parameters.AddWithValue("@Description", Profile.Orders.SCart.GetCartDescription());
cmd0.Parameters.Add("@PaymentType", SqlDbType.Bit).Value = Profile.Orders.SCart.PaymentType;
cmd0.Parameters.Add("@Delivery", SqlDbType.Bit).Value = Profile.Orders.SCart.Delivery;
cmd0.Parameters.AddWithValue("@Total", Profile.Orders.SCart.Total);
try
{
using (connection)
{
connection.Open();
cmd0.ExecuteNonQuery();
}
string selectSQL = "SELECT OrderID FROM Orders WHERE UserName=@UserName AND DateCreated=@DateCreated";
SqlCommand cmd1 = new SqlCommand(selectSQL, connection);
cmd1.Parameters.AddWithValue("@UserName", Profile.UserName);
cmd1.Parameters.AddWithValue("@DateCreated", Profile.Orders.SCart.DateCreated());
SqlDataReader reader;
using (connection)
{
connection.Open();
reader = cmd1.ExecuteReader();
reader.Read();
OrderID = (int)reader["OrderID"];
reader.Close();
}
// Store registered customer information for later usage..
if (!Profile.IsAnonymous)
{
string insertSQL2 = "";
insertSQL2 += "INSERT INTO CategoriesInAnOrder (";
insertSQL2 += "OrderID, CategoryID, Quantity) VALUES (@OrderID, @CategoryID, @Quantity)";
foreach (CartItem item in Profile.Orders.SCart.Items)
{
SqlCommand cmd2 = new SqlCommand(insertSQL2, connection);
cmd2.Parameters.AddWithValue("@OrderID", OrderID);
cmd2.Parameters.AddWithValue("@CategoryID", item.CategoryID);
cmd2.Parameters.AddWithValue("@Quantity", item.Quantity);
using (connection)
{
connection.Open();
cmd2.ExecuteNonQuery();
}
}
}
}
catch (Exception err)
{
pnlWizard.Visible = false;
lblError.Text = err.Message;
}
}
可能值得一提的是,我在 SuperClass 中放置了一个 SqlConnection 对象,因此每个子类(如包含上述方法的子类)都继承了该属性。
共享的 SqlConnection 对象设置如下:
protected SqlConnection connection = new SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["DefaultConnectionString"].ConnectionString);
对不起我的英语...我是意大利人
最佳答案
我觉得
using(connection)
可能是您问题的根源。
调用完成后, using() 将导致在连接上调用 Dispose(),但您的连接仅被实例化一次。
下次你来用它,它不会处于健康状态!
考虑每次创建一个新连接:
protected SqlConnection connection
{
get
{
return new SqlConnection
(System.Web.Configuration.WebConfigurationManager.ConnectionStrings
["DefaultConnectionString"].ConnectionString);
}
}
关于c# - 插入后未启动 ConnectionString!,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6573157/