下面是通过DataSet在student数据表中增加一个记录的代码
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" Debug="true" %>
<%@ import Namespace="System.Data "%>
<%@ import Namespace="System.Data.SqlClient" %>
<html>
<head runat="server">
<title>无标题页</title>
</head>
<script language="c#" runat="server" >
void page_load(object serder,EventArgs e)
{
SqlConnection sqlcon=new SqlConnection("Data Source=127.0.0.1;uid=sa;pwd=;Initial Catalog=chapter");
DataSet ds=new DataSet();
sqlcon.Open();
SqlDataAdapter sqld=new SqlDataAdapter("select * from student",sqlcon);
SqlCommandBuilder objcmdbld=new SqlCommandBuilder(sqld);
sqld.Fill(ds,"tabstudent");
DataRow drow;
drow=ds.Tables["tabstudent"].NewRow ();
drow[0]="97070705";
drow[1]="huang";
drow[2]=30;
drow[3]="bejing";
ds.Tables["tabstudent"].Rows.Add(drow);
ds.Tables["tabstudent"].AcceptChanges();
sqld.Update(ds, "tabstudent");
dg.DataSource=ds.Tables["tabstudent"].DefaultView;
dg.DataBind();
sqlcon.Close();
sqlcon=null;
labContent.Text+="添加记录成功";
}
</script>
<body>
<form id="form1" runat="server">
<asp:DataGrid ID="dg" runat="server" /><br />
<asp:Label ID="labContent" runat="server" /><br />
</form>
</body>
</html>
成功运行后结果如下:
然后我再用以下代码查找数据库表记录:
<%@ Page Language="C#" %>
<%@ import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>实验(5)-显示所有用户的情况</title>
</head>
<script language="c#" runat="server" >
void page_load(object serder, EventArgs e)
{
SqlConnection sqlcon = new SqlConnection("Data Source=127.0.0.1;uid=sa;pwd=;Initial Catalog=chapter");
DataSet ds = new DataSet();
sqlcon.Open();
SqlDataAdapter sqld = new SqlDataAdapter("select * from student", sqlcon);
sqld.Fill(ds, "tabstudent");
dg.DataSource = ds.Tables["tabstudent"].DefaultView;
dg.DataBind();
sqlcon.Close();
sqlcon = null;
labContent.Text += "查找成功";
}
</script>
<body>
<form id="form1" runat="server">
<asp:DataGrid ID="dg" runat="server" /><br />
<asp:Label ID="labContent" runat="server" /><br />
</form>
</body>
</html>
结果如下:
发现刚刚先提交的记录并没有更新到数据库表中啊,这是为什么,哪里错了呢
我的数据库名为chapter,,表student,,字段说明如下
studentid char(8)
name char(10)
age int (4)
address varchar(50)
问题转移到十七楼
[此贴子已经被作者于2007-4-24 23:38:45编辑过]