
<% @Import Namespace="System.Data.SqlClient" %>
<HTML>
	<HEAD>
		<title>数据库异常处理示例</title>
		
		<script language=C# runat=server>
		
			void Page_Load(object sender, System.EventArgs e)
			{
				Connection();
			}

			public void Connection()
			{
				// 连接字符串
				string ConnectionString = System.Configuration.ConfigurationSettings.AppSettings["ConnectionSqlServer"];
				string Sql = "1SELECT * FROM Employees";

				// 创建 SqlConnection 和 SqlCommand 对象
				SqlConnection thisConnection = new SqlConnection(ConnectionString);
				SqlCommand thisCommand = new SqlCommand(Sql, thisConnection);
				try
				{
					thisConnection.Open();
					thisCommand.ExecuteNonQuery();
					myLabel.Text = "未出现异常！";
				}
				catch(SqlException ex)
				{
					// 异常信息显示
					myLabel.Text = "<b>数据库执行错误</b><br>";
					myLabel.Text += "错误信息：" + ex.Source + "<br>";
					myLabel.Text += "错误行号：" + ex.LineNumber +"行<br>";
					myLabel.Text += "详细信息：" + ex.Message + "<br>";
				}
				finally
				{
					// 关闭数据库连接
					thisConnection.Close();
				}
			}
			
		</script>
		
	</HEAD>
	<body>
		<form id="Form1" method="post" runat="server">
			<h3>数据库异常处理示例</h3>
			<asp:Label ID=myLabel Runat=server></asp:Label>
		</form>
	</body>
</HTML>
