asp.net與sql資料庫操作常用語句

來源:互聯網
上載者:User
一、在web.config中添加資料庫連接:

    找到<appSettings />或<connectionStrings />,修改成為:

    <appSettings>

        <add key="SubTitle" value="上海亞東國際貨物有限公司拼箱保系統"/>

        <add key="connString" value="server=localhost;Initial Catalog=Demo;Integrated Security=True"/>

        <!--<add key="connString" value="server=127.0.0.1;uid=sa;pwd=sa;database=Demo "/>-->

    </appSettings>

    其中的key(或稱name)可以自己定義,以後在程式中要使用這個名字。

 

 

二、資料庫常用的代碼:    1).開啟資料庫進行操作:

SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["dataconnection"].ConnectionString);// 對資料庫連接執行個體化<br /> try<br /> {<br /> conn.Open();//開啟資料庫<br /> }<br /> catch (SqlException ex)<br /> {<br /> throw new Exception(ex.Message, ex);//拋出異常<br /> //Response.Write("<mce:script type="text/javascript"><!--<br />alert('出錯了!請聯絡管理員')<br />// --></mce:script>");//給使用者一個友好的提示資訊<br /> }<br /> finally<br /> {<br /> conn.Close();//關閉資料庫<br /> }
     注意:應添加System.Configuration引用

 

    2).使用gridview常用操作:

        添加System.Configuration引用
        添加System.Data引用
        添加System.Data.SqlClient引用
    
    在網頁初始化事件中的代碼:

SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["dataconnection"].ConnectionString);//對資料庫連接執行個體化<br /> string sql="select * from 表名";<br /> try<br /> {<br /> conn.Open();//開啟資料庫<br /> SqlDataAdapter myadp = new SqlDataAdapter(sql, conn);//對SqlDataAdapter執行個體化,執行sql中的語句<br /> DataSet myds = new DataSet();//對DataSet執行個體化<br /> myadp.Fill(myds);//將SqlDataAdapter填充到DataSet中<br /> GridView1.DataSource = myds;//指定GridView的數庫源為DataSet<br /> GridView1.DataBind();//對GridView進行綁定<br /> }<br /> catch (SqlException ex)<br /> {<br /> throw new Exception(ex.Message, ex);//拋出異常<br /> //Response.Write("<mce:script type="text/javascript"><!--<br />alert('出錯了!請聯絡管理員')<br />// --></mce:script>");//給使用者一個友好的提示資訊<br /> }<br /> finally<br /> {<br /> conn.Close();//關閉資料庫<br /> } 

 

    GridView分頁操作:
    設定GridViw的allowPaging(是否分頁)屬性為True,設定PageSize(每頁顯示條目數)數量,添加PageIndexChanging事件,在事件中添加如下代碼:
     GridView1.PageIndex = e.NewPageIndex;//當頁數發生改變時,索引到新頁
     GridView1.DataBind();//重新綁定GridView

 

在gridview添加刪除功能步驟:

   a、在gridview的<column>中增加

<asp:TemplateField><ItemTemplate></p><p> </ItemTemplate></asp:TemplateField> 

    b、在上一步中的中間增加一個LinkButton控制項設定屬性OnCommand="事件名稱",ComandArgument='<%#Eval("需要綁定的欄位")%>'
    c、在背景cs檔案中手動增加事件:

protected void 事件名稱(object sender, CommandEventArgs e)<br /> {</p><p> } 

    注意事件名稱與第2步的OnCommand="事件名稱"中的事件一致
   d、在事件中設定:

int id = int.Parse((string)e.CommandArgument); 

    註:id即為需要刪除的ID號碼,這句的功能為根據ComandArgument中的值擷取需要刪除的ID號
    e、在事件中執行刪除代碼:

int id = int.Parse((string)e.CommandArgument);//定義整型變數id接收LinkButton中的CommandArgument屬性中的值<br /> SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["dataconnection"].ConnectionString);// 對資料庫連接執行個體化<br /> string sql = "delete from admin where adminid="+id;//定義sql刪除語句<br /> try<br /> {<br /> conn.Open();//開啟資料庫<br /> SqlCommand mycmd = new SqlCommand(sql, conn);//對 SqlCommand進行執行個體化<br /> mycmd.ExecuteNonQuery();//執行SqlCommand<br /> Response.Redirect("admin_admin_manage.aspx");//轉向<br /> }<br /> catch (SqlException ex)<br /> {<br /> throw new Exception(ex.Message, ex);//拋出異常<br /> //Response.Write("<mce:script type="text/javascript"><!--<br />alert('出錯了!請聯絡管理員')<br />// --></mce:script>");//給使用者一個友好的提示資訊<br /> }<br /> finally<br /> {<br /> conn.Close();//關閉資料庫<br /> } 

 

    刪除的Sql語句格式:
    1.全部刪除:delete  from users
    2.刪除指定ID的記錄:delete  from users where id=1;
    3.刪除指定條件的記錄:delete from users where username='langhp'
    4.如果想在刪除時加入確認刪除的步驟,可以在LinkButton中加入如下屬性:OnClientClick="return confirm('確認刪除?')"

 

 

在gridview添加修改功能步驟:

    a、在gridview中增加

 

<asp:TemplateField><ItemTemplate></p><p> </ItemTemplate></asp:TemplateField> 

 

    b、在上一步中的中間增加一個LinkButton控制項設定屬性OnCommand="事件名稱",ComandArgument='<%#Eval("需要綁定的欄位")%>'
    c、在背景cs檔案中手動增加事件:

protected void 事件名稱(object sender, CommandEventArgs e)<br /> {</p><p> } 

    注意事件名稱與第2步的OnCommand="事件名稱"中的事件一致
    d、在事件中設定:

int id = int.Parse((string)e.CommandArgument); 

    註:id即為需要修改的ID號碼,這句的功能為根據ComandArgument中的值擷取需要刪除的ID號
    e.在事件中執行轉向命令,使其能夠轉向到新的網頁進行修改:

Response.Redirect("usermodify.aspx?id="+id); 

 

    f.在新的網頁中設計布局,以便使需要修改的內容初使化,然後在背景CS代碼檔案中網頁初使化事件前加入:
      然後在頁面初使化事件中根據sql語句查詢出需要修改的指定ID的記錄,並對頁面的控制項進行初始化:

SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["dataconnection"].ConnectionString);//對資料庫連接執行個體化<br /> id = int.Parse((string)Request.Params["id"]);//從地址欄中接收變數的值,即要修改的ID的值<br /> string sql = "select * from admin where adminid="+id;//定義sql語句,從資料庫中查詢指定ID的記錄<br /> try<br /> {<br /> conn.Open();//開啟資料庫<br /> SqlCommand mycmd = new SqlCommand(sql, conn);//對 SqlCommand進行執行個體化<br /> SqlDataReader mydr = mycmd.ExecuteReader();//執行SqlCommand<br /> if (mydr.Read())//如果有傳回值<br /> {<br /> txt_adminname.Text = mydr["adminname"].ToString().Trim();//對使用者名稱進行初始化<br /> }<br /> }<br /> catch (SqlException ex)<br /> {<br /> throw new Exception(ex.Message, ex);//拋出異常<br /> //Response.Write("<mce:script type="text/javascript"><!--<br />alert('出錯了!請聯絡管理員')<br />// --></mce:script>");//給使用者一個友好的提示資訊<br /> }<br /> finally<br /> {<br /> conn.Close();//關閉資料庫<br /> } 

 

 

    g.在修改按鈕事件中更新指定ID的記錄:
    update 表名 set 欄位名=值 where id=指定的id
    常用代碼:

SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["dataconnection"].ConnectionString);//對資料庫連接執行個體化<br /> string adminpass = txt_pass1.Text.ToString().Trim();//定義變數接收使用者名稱<br /> string adminname = txt_adminname.Text.ToString().Trim();//定義變數接收密碼<br /> string sql = "update admin set adminpass='"+adminpass+"' where adminname='"+adminname+"'";//定義 sql更新語句<br /> try<br /> {<br /> conn.Open();//開啟資料庫<br /> SqlCommand mycmd = new SqlCommand(sql, conn);//對SqlCommand執行個體化<br /> mycmd.ExecuteNonQuery();//執行Sqlcommand<br /> Response.Redirect("admin_admin_manage.aspx");//轉向<br /> }<br /> catch (SqlException ex)<br /> {<br /> throw new Exception(ex.Message, ex);//拋出異常<br /> //Response.Write("<mce:script type="text/javascript"><!--<br />alert('出錯了!請聯絡管理員')<br />// --></mce:script>");//給使用者一個友好的提示資訊<br /> }<br /> finally<br /> {<br /> conn.Close();//關閉資料庫<br /> } 

 

    h.將網頁轉向到需要的網頁,一般是顯示全部記錄的頁面添加資料記錄常用代碼:

       首先應先檢測是否有重名,例如使用者名稱不可重複,或標題不可重複等資訊
       然後在沒有重名的情況下,將記錄寫入資料庫:insert into(欄位1,欄位2)values(值1,值2)

<br /> SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["dataconnection"].ConnectionString);// 對資料庫連接執行個體化<br /> try<br /> {<br /> conn.Open();//開啟資料庫<br /> string adminname = txt_adminname.Text.ToString().Trim();//取得使用者輸入的使用者名稱<br /> string sql = "select adminname from admin where adminname='"+adminname+"'";//定義檢測的查詢語句<br /> SqlCommand mycmd = new SqlCommand(sql, conn);//對SqlCommand進行執行個體化<br /> SqlDataReader mydr = mycmd.ExecuteReader();//將執行結果返回到SqlDataReader中<br /> if (mydr.Read())//如果有重名,提示資訊<br /> {<br /> Response.Write("己存在");<br /> }<br /> else//不重名寫入資料庫<br /> {<br /> mydr.Close();//關閉SqlDataReader<br /> string adminpass = txt_adminpass1.Text.ToString().Trim();//取得使用者輸入的密碼<br /> string sql2 = "insert into admin(adminname,adminpass)values('"+adminname+"','"+adminpass+"')";//定義插入語句<br /> SqlCommand mycmd2 = new SqlCommand(sql2, conn);//對SqlCommand進行執行個體化<br /> mycmd2.ExecuteNonQuery();//執行<br /> Response.Redirect("admin_admin_manage.aspx");//轉向回管理頁<br /> }<br /> }<br /> catch (SqlException ex)<br /> {<br /> throw new Exception(ex.Message, ex);//拋出異常<br /> //Response.Write("<mce:script type="text/javascript"><!--<br />alert('出錯了!請聯絡管理員')<br />// --></mce:script>");//給使用者一個友好的提示資訊<br /> }<br /> finally<br /> {<br /> conn.Close();//關閉資料庫<br /> } 

 

單擊標題顯示具體新聞內容(gridview中的應用):
    1.在Gridview中加入模版列

 2.在兩者中加入HyperLink控制項,設定NavigateUrl屬性:
      NavigateUrl='<%#"顯示頁面的名稱.aspx?變數="+Eval("資料表中的欄位")%>'
      例:NavigateUrl='<%#"show.aspx?id="+Eval("newsid") %>'
      說明:資料表中的欄位一般為ID欄位!
    3.在HyperLink中加入<%#Eval("資料表中的欄位")%>
      例:<%#Eval("newstitle") %>
      說明:資料表中的欄位一般為標題欄位(因為要顯示的為標題)!
    4.設定TemplateField的HeaderText屬性
    5.建立ASPX頁面,並設計好頁面的布局
    6.在建立的頁面的初始化代碼中將指定ID的記錄選取出來,常見代碼:
SqlConnection conn = new<br />SqlConnection(ConfigurationManager.ConnectionStrings["dataconnection"].ConnectionString);//對資料庫<br />串連執行個體化<br /> try<br /> {<br /> conn.Open();//開啟資料庫<br /> int id = int.Parse((string)Request.Params["id"]);//注意ID為第2步中的變最名<br /> string sql = "select * from news where newsid="+id;<br /> SqlCommand mycmd = new SqlCommand(sql, conn);<br /> SqlDataReader mydr = mycmd.ExecuteReader();<br /> if (mydr.Read())<br /> {<br /> Label1.Text = mydr["newscontent"].ToString().Trim();<br /> }<br /> }<br /> catch (SqlException ex)<br /> {<br /> throw new Exception(ex.Message, ex);//拋出異常<br /> //Response.Write("<mce:script type="text/javascript"><!--<br />alert('出錯了!請聯絡管理員')<br />// --></mce:script>");//給使用者一個友好的提示<br />資訊<br /> }<br /> finally<br /> {<br /> conn.Close();//關閉資料庫<br /> } 

 

=========================================        其他技巧           =======================================

 

MD5加密:
        對資料進行加密是一種常用的技術,一般用在對密碼進行加密。
        加密有兩種方式,一種為雙向的(可以加密,也可以解密),另外一種為單向的(只能加密,不能解密),MD5加密屬於單向加密。

    使用方法:
    1.在需要進行加密的頁面中引用System.Web.Security名稱空間
    2.對需要加密的字串進行加密:
      例:

          string usrpwd=FormsAuthentication.HashPasswordForStoringInConfigFile(TextBox1.Text,"MD5");<br />string pwd=FormsAuthentication.HashPasswordForStoringInConfigFile(字串變數,"MD5");
    3.注意,加密後的字串長度為32位,要修改資料表中對應的欄位長度。
    *****注意:admin加密後的字串為:21232F297A57A5A743894A0E4A801FC3,這個備用!!!

 

 

GridView中,對於超長欄位(例如標題的處理)
    三元運算子:條件?條件為真時:條件為假時
    Substring函數(截取字串):Substring(開始位置,取幾位)
    執行個體:
            <%#Eval("欄位名").ToString().Length>10?Eval("欄位名").ToString().Substring(0,10)+"……":Eval("欄位名").ToString()%> 

 

 

屬於檔架頁面的轉向時,應使用
    Response.Write("<mce:script language='javascript'><!--<br />alert('資訊!');window.parent.location.href='要轉向的網頁';<br />// --></mce:script>"); 

 

如何在Web.config檔案中設定變數資訊:
    在web.config中的appSettings節下增加一個值:
     <add value="值" key="名稱"/>
    在CS頁面中讀取:

    ConfigurationManager.AppSettings["appSettings中的key名"].ToString(); 

 

 

 

 

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.