我在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