sqlcommandexample.aspx

来自「asp.net专家200问(含源代码解决法案」· ASPX 代码 · 共 55 行

ASPX
55
字号

<% @Import Namespace="System.Data" %>
<% @Import Namespace="System.Data.SqlClient" %>
<HTML>
	<HEAD>
		<title>使用 SqlCommand 执行SQL命令示例</title>
		<script language="C#" runat="server">
	
			void Page_Load(object sender, System.EventArgs e)
			{
				// 连接字符串
				string ConnStr = System.Configuration.ConfigurationSettings.AppSettings["ConnectionSqlServer"];

				// 创建SqlConnection对象
				// 创建Command对象
				SqlConnection thisConnection = new SqlConnection(ConnStr);
				SqlCommand thisCommand = new SqlCommand();

				// 关联Connection对象
				// 赋值SQL语句到CommandText属性
				// 指定命令类型是Sql语句
				thisCommand.Connection = thisConnection;
				thisCommand.CommandText = "SELECT COUNT(*) FROM Employees";
				thisCommand.CommandType = CommandType.Text;

				try
				{
					// 打开数据库连接
					thisCommand.Connection.Open();

					// 获取查询结果
					myLabel.Text = thisCommand.ExecuteScalar().ToString();
				}
				catch(SqlException ex)
				{
					// 如果出现异常,在Label标签中显示异常信息
					myLabel.Text = ex.ToString();
				}
				finally
				{
					// 关闭数据库连接
					thisCommand.Connection.Close();
				}
			}
	
		</script>
	</HEAD>
	<body>
		<form id="Form1" method="post" runat="server">
			<h3>使用 SqlCommand 执行SQL命令示例</h3>
			Employees表的记录数是:<asp:Label id="myLabel" runat="server"></asp:Label>
		</form>
	</body>
</HTML>

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?