最近在学习asp.net,使用的是《asp.net3.5从入门到精通》,到ADO.net这个章节的时候,有个部分是使用Command对象修改表中的信息。
我用的是visual studio 2010 + SQL Server 2008 R2.
页面布局Default.aspx是这样的:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.style1
{
width: 100%;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<table class="style1">
<tr>
<td>
商品名称:</td>
<td>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</td>
</tr>
<tr>
<td>
商品类型:</td>
<td>
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
</td>
</tr>
<tr>
<td>
商品价格:</td>
<td>
<asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>
</td>
</tr>
</table>
</div>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ProductConnectionString %>"
SelectCommand="SELECT * FROM [UserInfo]"></asp:SqlDataSource>
</form>
</body>
</html>
webconfig配置文件:
<connectionStrings>
<add name="ProductConnectionString" connectionString="Data Source=PC-201108231512\SQLEXPRESS;Initial Catalog=Product;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
Default.aspx.cs中的内容是这样的:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
public partial class _Default : System.Web.UI.Page
{
private SqlDataReader myReader;
protected void Page_Load(object sender, EventArgs e)
{
//定义连接字符串
string strConn = ConfigurationManager.ConnectionStrings["ProductConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(strConn);
//打开连接
conn.Open();
//更新语句,将数据库中的第一条信息的Price更新为100
string update = "update UserInfo set Price = '100' where ID = 1";
SqlCommand cmd = new SqlCommand(update, conn);
//查询语句,查询数据表中的第一条已更新的信息
string select = "select Name,Type,Price from UserInfo where ID = 1";