gpt4 book ai didi

c# - 系统无效操作异常

转载 作者:行者123 更新时间:2023-11-30 21:50:05 25 4
gpt4 key购买 nike

我正在尝试将其保存到我的数据库中,但我一直收到此错误

System.InvalidOperationException

这是我的代码。

 protected void btnSend_Click(object sender, EventArgs e)
{
con.Open();
cmd = new SqlCommand(@"INSERT INTO orders2
(orderName,orderFile,orderType,orderPrice,orderQuantity,orderShipped)
VALUES
('"+DropDownList1.SelectedValue+"','"+lblFile.Text+"','"+lblPrice.Text+"','"+txtQuantity.Text+"','"+DateTime.Now+"')",con);
cmd.ExecuteNonQuery();
con.Close();
lblFinished.Text = "Order has been submitted for process.";

}

最佳答案

WhoAmI 可能是正确的,但是您的代码可以大大改进以避免其他问题并允许您不允许未处理的异常。

我已经在代码中直接添加了额外的注释:

try
{

// SqlConnection is disposable, so it is recommended to dispose it (using calls Dispose() for you)
using (var con = new SqlConnection(connStr))
{
con.Open();

// this is missing from your code and might the errors actual cause
// SqlCommand is also disposable
using (var cmd = con.CreateCommand())
{
// is is strongly recommended to construct parameterized commands
// to avoid SQL injection (check this - https://technet.microsoft.com/en-us/library/ms161953(v=sql.105).aspx)
cmd.Text = @"
INSERT INTO orders2
(orderName,orderFile,orderType,orderPrice,orderQuantity,orderShipped)
VALUES (@orderName, @orderFile, @orderType, @orderPrice, @orderQuantity, @orderShipped)";

// the parameters - SqlCommand infers parameter type for you
cmd.AddWithValue("@orderName", DropDownList1.SelectedValue);
cmd.AddWithValue("@orderFile", lblFile.Text);
cmd.AddWithValue("@orderType", theMissingParametersForOrderType);
// some conversion might be needed here, as I expect the price to be some number
// with a fixed number of decimals
// e.g. Convert.ToDecimal(lblPrice.Text)
cmd.AddWithValue("@orderPrice", lblPrice.Text);
// same convertion issue as for price
cmd.AddWithValue("@orderQuantity", txtQuantity.Text);
cmd.AddWithValue("@orderShipped", DateTime.Now);
}
}
}
// there are several Exceptions that can be raised and treated separately
// but this at least you can do
catch (Exception exc)
{
// log the error somewhere
// put a breakpoint just below to inspect the full error details
}
// this is executed even if an exception has occurred
finally
{
if (con != null && con.State != ConnectionState.Closed)
con.Close();
}

附带说明一下,此代码属于数据层,不属于表示层。考虑将其包含在另一个程序集中。

关于c# - 系统无效操作异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36538783/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com