這裏是我的代碼爲什麼它總是捕捉塊並且不執行「cmd.ExecuteNonQuery();」
protected void Button2_Click(object sender, EventArgs e)
{
try
{
string constr = @"Data Source=ADMIN\LOCALHOST;Initial Catalog=maha;Integrated Security=True";
using (SqlConnection con = new SqlConnection(constr))
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
string query = "Insert into [dbo].[student] ([ID],[NAME],[DOB],[GENDER]) Values ('@id','@name','@dob','@gender')";
Label3.Text = "execute";
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@id", TB1.Text);
cmd.Parameters.AddWithValue("@name", TB2.Text);
cmd.Parameters.AddWithValue("@dob", TB3.Text);
cmd.Parameters.AddWithValue("@gender", rm);
cmd.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
throw new Exception(ex.ToString());
}
}
protected void Button3_Click(object sender, EventArgs e)
{
try
{
string constr = @"Data Source=ADMIN\LOCALHOST;Initial Catalog=maha;Integrated Security=True;";
using (SqlConnection con = new SqlConnection(constr))
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
string query = "Update [dbo].[student] set [ID][email protected],[NAME][email protected], [DOB][email protected]," +
"[GENDER][email protected] Where [ID][email protected]";
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@id", TB1.Text);
cmd.Parameters.AddWithValue("@name", TB2.Text);
cmd.Parameters.AddWithValue("@dob", TB3.Text);
cmd.Parameters.AddWithValue("@gender", rm);
cmd.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
throw new Exception(ex.ToString());
}
}
catch塊的異常是什麼? – Mark
因爲它可能會在'con.Open()'或其他地方崩潰?請使用斷點並按照說明查看它的崩潰位置和原因。 – Furtiro
實際上,我的錯誤是在將TB3.Text轉換爲日期格式時發生的?因爲在我的數據庫中,dob數據類型是日期。現在我正在使用cmd.Parameters.AddWithValue(「@ dob」,DateTime.Parse(TB3.Text));但他們仍然是一個錯誤「System.Data.SqlClient.SqlException(0x80131904):轉換日期和/或時間從字符串轉換失敗。」 –