ASP:ado.net 实例向数据库添加数据。

我在这使用的是老师给的数据库


1,web窗体设计。

设计添加图书窗体,窗体属性有图书种类(下拉列表框控件),图书名称,作者,编号,出版社,价格均为文本框,日期(第三方日期控件),两个按钮分别为添加和清空。

 

2,连接数据库。

构建连接文本strcn,通过ConfigurationManager找到配置文件,然后通过ConnectionStrings找到配置文件中的节点connectionStrings通过名为strcon找到连接文本。

创建连接对象cn,通过SqlConnection对象载入strcn。

 1 string strcn = ConfigurationManager.ConnectionStrings["strcon"].ConnectionString; 2 SqlConnection cn = new SqlConnection(strcn); 

3,构建命令文本和命令对象。(连接成功了,就要告诉数据库该干什么事情)

构建命令文本comtext,让数据库执行添加操作,创建连接对象com,通过SqlCommand对象载入命令文本comtext和连接对象cn

1 string comtext = "INSERT INTO BookShopOnNet.dbo.NewBook(BookTypeId,BookName,Author,ISBN,Publisher,PublishDate,Price)VALUES(@BookTypeId,@BookName,@Author,@ISBN,@Publisher,@PublishDate,@Price)";
2 SqlCommand com = new SqlCommand(comtext, cn);

4,构建参数数组。

因为在传递参数时有多个参数,这时候我们就可以通过构建参数数组的方法来传递参数。通过这样的格式创建数组 int [ ]  abc = new int []{1,2,3,4,5, };的格式创建数组,而我们asp中创建参数数组的类型是SqlParameter 且带的是参数不是整数所以在每传一个参数时都要new一个新的SqlParameter还要将他的参数和值带进去。

1 SqlParameter[] paras = new SqlParameter[]{
2                 new SqlParameter("@BookTypeId",this.dpdType.Text),
3                 new SqlParameter("@BookName",this.txtName.Text),
4                 new SqlParameter("@Author",this.txtXinM.Text),
5                 new SqlParameter("@ISBN",this.txtID.Text),
6                 new SqlParameter("@Publisher",this.txtCBS.Text),
7                 new SqlParameter("@PublishDate",this.txtdata.Text),
8                 new SqlParameter("@Price",this.txtPrice.Text), 
9             };

完了之后还要将创建好的数组添加到 SqlCommand对象的参数集SqlParameters 中。

 1 com.Parameters.AddRange(paras); 

5,打开连接执行。

cn.open();为打开连接,cn.close();为关闭连接。因为打开连接的过程中可能会出错,所以要养成习惯使用try...catch....finally捕捉异常。那么我们怎么才能知道有没有添加成功呢,在这里我们要添加一个变量记录每次执行程序是受影响的行数,如果受影响的行数大于0那么就是添加成功,反之添加失败。

 

 1 try
 2   {
 3                 cn.Open();
 4                 int result=com.ExecuteNonQuery();
 5                 if(result>0){
 6                     Response.Write("<script>alert('添加成功!')</script>");
 7                 }
 8                 else
 9                 {
10                     Response.Write("<script>alert('添加失败!')</script>");
11                 }
12             }
13             catch
14             {
15                 Response.Write("<script>alert('运行异常!')</script>");
16             }
17             finally
18             {
19                 cn.Close();
20             }

6,清空按钮事件。

就是把每个文本框清空,每个下来列表框设为默认值。

1 this.dpdType.Text = "";
2 this.txtName.Text = "";
3 this.txtXinM.Text = "";
4 this.txtID.Text = "";
5 this.txtCBS.Text = "";
6 this.txtdata.Text = "";
7 this.txtPrice.Text = "";
8 dpdType.Focus();//光标定位到文本框

 

posted @ 2020-03-30 15:11  奔跑吧rookie  阅读(967)  评论(0编辑  收藏  举报