
<% @Import Namespace="System.Data" %>
<HTML>
	<HEAD>
		<title>访问数据库的通用代码示例</title>
		<script language=C# runat=server>
		
			void ExecuteButton_Click(object sender, System.EventArgs e)
			{
				// 获取数据库类型、连接字符串和 SQL 命令
				string selResult = DBDropDownList.SelectedValue;
				string ConnStr = ConnStrTextBox.Text;
				string query = SqlTextBox.Text;

				System.Data.IDbConnection idbConn = null;

				// 根据数据库类型，创建相应的 Connection 对象
				switch(selResult)
				{
					case "SqlServer":
						idbConn = new System.Data.SqlClient.SqlConnection(ConnStr);
						break;
					case "Oracle":
						idbConn = new System.Data.OracleClient.OracleConnection(ConnStr);
						break;
					case "Access":
						idbConn = new System.Data.OleDb.OleDbConnection(ConnStr);
						break;
					case "DB2":
						idbConn = new System.Data.Odbc.OdbcConnection(ConnStr);
						break;
					default:
						idbConn = new System.Data.OleDb.OleDbConnection(ConnStr);
						break;
				}
				Execute(idbConn, query);			
			}

			void Execute(System.Data.IDbConnection idbConnection, string query)
			{
				// 使用 CreateCommand() 方法生成 Command 对象
				System.Data.IDbCommand idbCommand = idbConnection.CreateCommand();

				idbCommand.CommandText = query;
				try
				{
					idbConnection.Open();
					idbCommand.ExecuteNonQuery();
					ResultLabel.Text = "操作执行成功！";
				}
				catch(Exception ex)
				{
					ResultLabel.Text = ex.Message;
				}
				finally
				{
					idbConnection.Close();
				}
			}

		</script>

	</HEAD>
	<body>
		<form id="Form1" method="post" runat="server">
			<h3>访问数据库的通用代码示例</h3>
			请输入连接字符串：
			<asp:TextBox id="ConnStrTextBox" runat="server" Width="450px"></asp:TextBox><BR>
			请输入SQL语句：
			<asp:TextBox id="SqlTextBox" runat="server" Width="424px"></asp:TextBox><BR>
			<asp:DropDownList id="DBDropDownList" runat="server">
				<asp:ListItem Value="SqlServer">SqlServer</asp:ListItem>
				<asp:ListItem Value="Oracle">Oracle</asp:ListItem>
				<asp:ListItem Value="Access">Access</asp:ListItem>
				<asp:ListItem Value="DB2">DB2</asp:ListItem>
			</asp:DropDownList>
			<BR><BR>
			<asp:Button id="ExecuteButton" 
					runat="server" Text="执行数据库操作" 
					OnClick="ExecuteButton_Click">
			</asp:Button>
			<BR><BR>
			<asp:Label id="ResultLabel" runat="server">操作结果</asp:Label>
		</form>
	</body>
</HTML>
