我在SQL Server Management Express中有一个名为“Table_1”的表。我已经成功地将我的ASP程序连接到数据库。我已经编码了以下编码以便在数据库中插入数据。如何在使用ASP.NET的插入代码中处理异常?
ExecuteNonQuery: Connection property has not been initialized.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: ExecuteNonQuery: Connection property has not been initialized.
Source Error:
Line 34: {
Line 35: SqlCommand hi = new SqlCommand("insert into Table_1 values('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "','" + TextBox4.Text + "','" + TextBox5.Text + "','" + TextBox6.Text + "'),conn");
Line 36: hi.ExecuteNonQuery();
Line 37: conn.Close();
Line 38: }
请帮我一个想法,以清除异常:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
namespace k2
{
public partial class _Default : System.Web.UI.Page
{
SqlConnection conn = new SqlConnection("Data Source=ARTHY/SQLEXPRESS;Initial Catalog=k2;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
conn.Open();
}
catch
{
SqlCommand hi = new SqlCommand("insert into Table_1 values('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "','" + TextBox4.Text + "','" + TextBox5.Text + "','" + TextBox6.Text + "'),conn");
hi.ExecuteNonQuery();
conn.Close();
}
}
}
}
当我试图插入任何数据,我如下得到一个例外。
首先,为什么这个代码在catch块中,而它应该在'conn.Open()'之后? –
我刚刚尝试清除异常。在给try和catch块之前,例外是在“conn.Open();”。然后在实现try和catch之后,它转到“hi.ExecuteNonQuery();”。 – kalyan