将行插入数据库时​​出现异常

时间:2012-10-19 08:07:49

标签: c# asp.net

我已编写此代码以在数据库中插入一行:

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["earchConnectionString"].ConnectionString);
//string insCmd = "Insert into [node] (title, parent_id, oid, display, linkById, customLinks, contentType) values (@title, @parent_id, @oid, @display, @linkById, @customLinks, @contentType)";
string insCmd = "Insert into [node] (title) values (@title)";
SqlCommand insertUser = new SqlCommand(insCmd, con);
insertUser.Parameters.AddWithValue("@title", TextBoxTitle.Text);

try
{
    insertUser.ExecuteNonQuery();
    con.Close();
    Response.Redirect("addNode.aspx");
    Label1.Text = "update success";

}
catch (Exception er)
{
    Label1.Text = er.StackTrace;
}

堆栈跟踪:

at System.Data.SqlClient.SqlConnection.GetOpenConnection(String method)
at System.Data.SqlClient.SqlConnection.ValidateConnectionForExecute(String method, SqlCommand command)
at System.Data.SqlClient.SqlCommand.ValidateCommand(String method, Boolean async)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at Admin_addNode.Button1_Click(Object sender, EventArgs e)
in c:\inetpub\web1\Admin\addNode.aspx.cs:line 52

任何人都知道这是什么问题?

1 个答案:

答案 0 :(得分:4)

在执行con.Open()

之前先致电ExecuteNonQuery()
con.Open();
insertUser.ExecuteNonQuery();