操作資料庫的方式(三種)

來源:互聯網
上載者:User

  在應用程式和Web開發過程中,資料庫的操作可以分這麼三種,第一種,直接寫硬SQL代碼,不要參數,第二種,直接寫硬代碼,要參數,第三種,調用預存程序。

  我們以一個登入模組為例,現在頁面有兩文字框,一按紐,實現驗證使用者名稱密碼的功能。第一種方法主要代碼如下:

SqlConnection conn =new  SqlConnection                   

("server=;database=news2;uid=sa;pwd=");
conn.Open();
SqlCommand cmd=new SqlCommand();
cmd.CommandText="select count(*)from users

where name='"+this.TextBox1.Text+"'and pwd='"+this.TextBox2.Text+"'";cmd.Connection=conn;int i=(int)cmd.ExecuteScalar();Response.Write(i.ToString());if(i==1){Response.Redirect("add.aspx");}else{Label1.Text="error!"}

  第二種途徑  

SqlConnection conn =new  SqlConnection("server=;database=news;uid=sa;pwd=");
conn.Open();//開啟資料庫
SqlCommand cmd=new SqlCommand();//建立命令對象
cmd.CommandText="select count(*)from users where name=@name and pwd=@pwd";
cmd.Connection=conn;//設定串連
SqlParameter p= new SqlParameter("@name",SqlDbType.Char,10);
//定義參數
p.Value=this.TextBox1.Text;
cmd.Parameters.Add(p);//添加參數到集合
p= new SqlParameter("@pwd",SqlDbType.Char,10);
p.Value=this.TextBox2.Text;
cmd.Parameters.Add(p);
int i=(int)cmd.ExecuteScalar();
if(i==1)
{
Response.Redirect("add.aspx");}
else
{
Label1.Text="error!"
}

  第三種途徑

SqlConnection conn =new  SqlConnection("server=;database=news;uid=sa;pwd=");
conn.Open();//開啟資料庫
SqlCommand cmd=new SqlCommand();//建立命令對象
cmd.CommandText=" checkLogin";//設定命令文本
cmd.CommandType=CommandType.StoredProcedure;
//設定文本類型
cmd.Connection=conn;//設定串連
SqlParameter p= new SqlParameter("@name",SqlDbType.Char,10);
//定義參數
p.Value=this.TextBox1.Text;
cmd.Parameters.Add(p);//添加參數到集合
p= new SqlParameter("@pwd",SqlDbType.Char,10);
p.Value=this.TextBox2.Text;
cmd.Parameters.Add(p);
int i=(int)cmd.ExecuteScalar();
if(i==1)
{
Response.Redirect("add.aspx");}
else
{
Label1.Text="error!"
}

  接下來對這三種方法做分析:

  第一方法不能防範SQL注入式方式攻擊,比如在第一個文字框輸入asd'or's'='s 第二個同樣輸入asd'or's'='s ,可以發現成功通過驗證。

  第二種直接寫硬SQL代碼,事實上不是每個人都能寫出優良的SQL代碼來,可以由資料庫管理員或工程師來寫,這樣,一方面減輕程式員的工作,另一方面也可以使資料庫與應用程式保持獨立,這樣有利於系統的移植與維護。

  第三種是推薦使用的,因為它是目前效率較高安全性較好的一種資料庫操作方式。
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.