三種操作數(shù)據(jù)庫(kù)的途徑

字號(hào):


    操作數(shù)據(jù)庫(kù)可以分這么三種,第一種,直接寫硬SQL代碼,不要參數(shù),第二種,直接寫硬代碼,要參數(shù),第三種,調(diào)用存儲(chǔ)過(guò)程。
    我們以一個(gè)登錄模塊為例,現(xiàn)在頁(yè)面有兩文本框,一按紐,實(shí)現(xiàn)驗(yàn)證用戶名密碼的功能。第一種方法主要代碼如下:
    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();//打開(kāi)數(shù)據(jù)庫(kù)
    SqlCommand cmd=new SqlCommand();//建立命令對(duì)象
    cmd.CommandText="select count(*)from users where and ";
    cmd.Connection=conn;//設(shè)置連接
    SqlParameter p= new SqlParameter("@name",SqlDbType.Char,10);
    //定義參數(shù)
    p.Value=this.TextBox1.Text;
    cmd.Parameters.Add(p);//添加參數(shù)到集合
    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();//打開(kāi)數(shù)據(jù)庫(kù)
    SqlCommand cmd=new SqlCommand();//建立命令對(duì)象
    cmd.CommandText=" checkLogin";//設(shè)置命令文本
    cmd.CommandType=CommandType.StoredProcedure;
    //設(shè)置文本類型
    cmd.Connection=conn;//設(shè)置連接
    SqlParameter p= new SqlParameter("@name",SqlDbType.Char,10);
    //定義參數(shù)
    p.Value=this.TextBox1.Text;
    cmd.Parameters.Add(p);//添加參數(shù)到集合
    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!"
    }
    接下來(lái)對(duì)這三種方法做分析:
    第一方法不能防范SQL注入式方式攻擊,比如在第一個(gè)文本框輸入asd'or's'='s 第二個(gè)同樣輸入asd'or's'='s ,可以發(fā)現(xiàn)成功通過(guò)驗(yàn)證。
    第二種直接寫硬SQL代碼,事實(shí)上不是每個(gè)人都能寫出優(yōu)良的SQL代碼來(lái),可以由數(shù)據(jù)庫(kù)管理員或工程師來(lái)寫,這樣,一方面減輕程序員的工作,另一方面也可以使數(shù)據(jù)庫(kù)與應(yīng)用程序保持獨(dú)立,這樣有利于系統(tǒng)的移植與維護(hù)。
    當(dāng)然第三種是推薦使用的,好處呢!就是前面所寫的。