asp mysql添加数据_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 = newSqlParameter[]{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("");7 }8 else
9 {10 Response.Write("");11 }12 }13 catch
14 {15 Response.Write("");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();//光標定位到文本框
總結
以上是生活随笔為你收集整理的asp mysql添加数据_ASP:ado.net 实例向数据库添加数据。的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 接口 java性能_接口测试性能测试
- 下一篇: java 数组的get set_java