<HTML>
	<HEAD>
		<title>将DataSet的改动更新回SQL Server数据库</title>
		<% @Import Namespace="System.Data" %>
		<% @Import Namespace="System.Data.SqlClient" %>
		<script language="C#" runat="server">

			void Page_Load(object sender, System.EventArgs e)
			{
				AutoUpdateToDatabase();
			}

			private void AutoUpdateToDatabase()
			{
				// 连接字符串及 SQL 语句
				string ConnString = System.Configuration.ConfigurationSettings.AppSettings["ConnectionSqlServer"];
				string Sql = "SELECT CustomerID,CompanyName,Country FROM Customers";

				// 连接 SqlConnection 对象，并和 SqlDataAdapter 关联
				SqlConnection thisConnection = new SqlConnection(ConnString);
				SqlDataAdapter adapter = new SqlDataAdapter(Sql, thisConnection);

				// 创建 DataSet 对象
				DataSet data = new DataSet();

				// 创建 SqlCommandBuilder 对象，并和 SqlDataAdapter 关联
				SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
				adapter.Fill(data, "Customers");

				// 修改 DataSet 的内容
				data.Tables["Customers"].Rows[0]["CompanyName"] = "CompanyName1";
				data.Tables["Customers"].Rows[0]["Country"] = "AAAA";
				data.Tables["Customers"].Rows[1]["CompanyName"] = "CompanyName2";
				data.Tables["Customers"].Rows[1]["Country"] = "BBBB";

				// 在 DataSet 中新增行
				DataRow newRow = data.Tables["Customers"].NewRow();
				newRow["CustomerID"] = "New";
				newRow["CompanyName"] = "New CompanyName";
				newRow["Country"] = "New Country";
				data.Tables["Customers"].Rows.Add(newRow);

				// 从 DataSet 更新 SQL Server 数据库
				adapter.Update(data, "Customers");
			}

		</script>
	</HEAD>
	<body>
		<form id="Form1" method="post" runat="server">
			<h3>将DataSet的改动更新回SQL Server数据库</h3>
			<P>本示例第二次运行时会产生异常，这是因为受主键约束的表中不能插入重复记录。</P>
		</form>
	</body>
</HTML>
