【筆記】ADO.NET學習

來源:互聯網
上載者:User

標籤:

查詢和操作資料庫

  要想從資料庫中讀取多條記錄就必須用到Command對象的ExecuteReader()方法,該方法返回一個DataReader對象,通過其對象的程式就可以訪問資料庫。

基礎知識

conn.close();   //關閉之後還能開啟;

conn.dispose();  //直接銷毀不能再次利用,dispose內部有close方法;

    

認識DataReader對象

        使用其DataReader對象可以從資料庫中檢索唯讀資料,且每次只能從查詢結果中讀取一行到記憶體中,非常的快,使用其時不能對其進行修改,只能讀取。而且在讀取是一定要與資料庫連接,不能中斷連線。

要建立一個DataReader對象需要調用Command對象的ExecuteRead()方法,此方法傳回值就是一個DataReader對象,之後調用其對象的Reader()方法來讀取一行資料,{將其放在一個while迴圈中,這樣就可以將所有的值全部都顯示出來}

步驟:

1:建立Command對象

     string connSting=”Data Source=zhanghui; Initial Catalog=Ahui; User ID=sa; Pwd=111”

     sqlconnection  conn=new sqlconnection(connString);

     conn.open();

     string  sql=”saelect  count(*) from Student”;

     sqlCommand md=new sqlCommand(sql,conn);

2:調用Command的ExecuteReader()方法建立DataReader對象。

     sqlDataReader  dataReader=md.ExecuteReader();

3:使用其的Read()方法按行去讀取資料,此方法返回一個布爾類型,若讀到資料則返回true,否則返回false,此時用到了while迴圈。

   while(dataReader.read())

  {

      擷取資料集中的值;

  }

4:

  4.1讀取當前行的某列資料,可以像數組一樣進行索引,按下標進行查詢顯示。

        (string)dataReader[0];

  4.2還有一種方法也可以擷取當前行的某列資料。

       string name=dataReader.GetString(0);                //擷取其第一行的值。

5:關閉其DataReader對象,調用其Close()方法。

eg one : 在前台輸入使用者,看是否為資料庫表中的資料,若是則顯示成功,不是報錯。

Console.WriteLine("請輸入使用者名稱");
           string username = Console.ReadLine();
           //資料庫連接字串
           string connString = "Data Source=zhanghui;Initial Catalog=Ahui;User ID=sa;Pwd=111";
           //建立資料庫的串連
           SqlConnection conn = new SqlConnection(connString);
           conn.Open();  //開啟資料庫
           using (SqlCommand kfc = conn.CreateCommand())                                           //建立Command對象。
           {
               kfc.CommandText = "select * from Student where Name=  ‘"+username +"‘  ";   //SQL語句
               using (SqlDataReader read = kfc.ExecuteReader())
               {
                   if (read.Read())
                   {
                       Console.WriteLine("使用者存在");
                   }
                   else
                   {
                       Console.WriteLine("使用者錯誤");
                   }

               }
           }
           Console.WriteLine("開啟資料庫連接成功");
           conn.Close();        //關閉資料庫,切記每次用完之後一定要關閉資料庫。
           Console.ReadKey();

 

eg two :從資料庫中讀取資料,顯示在視窗中。

一般的注意事項

           User是關鍵字,一般情況下表名以T_開頭,欄位以F_開頭;,這樣做的好處是防止表名與欄位和系統的關鍵字重複,報錯。

           reader的GenString,GetInt32等方法只能接受整數參數,也就是序號用GetOrdinal方法根據列名動態得到序號。

特殊:  eg three :

   改變上一個登入程式,使用其count(*)來進行比較,來查看是否登入成功;

static void Main(string[] args)
        {
            Console.WriteLine("請輸入使用者名稱");
            string username = Console.ReadLine();
            Console.WriteLine("請輸入密碼");
            string password = Console.ReadLine();
            //資料庫連接字串
            string connString = "Data Source=zhanghui; Initial Catalog=Ahui; User ID=sa; Pwd=111";
            //建立資料庫連接
            SqlConnection conn=new SqlConnection(connString);
            //開啟資料庫
            conn.Open();
            using (SqlCommand  ka=conn.CreateCommand())
            {
                ka.CommandText = "select count(*) from login where UserName=‘"+username+"‘ and  Password=‘"+password+"‘ ";

                //當時在做的時候,不知道在UserName和Password之間加and,花費了很多的時間,最後才知道了,這是SQL文法裡面的知識。   
                int i = Convert.ToInt32(ka.ExecuteScalar());

               //在這裡的ka.ExecuteScalar()代表的就是ka.Command裡面傳出來的值。         

                if (i>0)
                {
                    Console.WriteLine("登入成功");   
                }
                else
                {
                    Console.WriteLine("使用者名稱或密碼錯誤?");
                }

            }
            Console.WriteLine("OK");
            Console.ReadKey();

但是為什麼我這樣子輸入的話,也會出現登入成功。

老師說這是一種注入漏洞,只要是登入名稱和資料庫中的登入名稱一樣,就可以顯示登入成功。

但是如果想避免情況的發生,就必須使用參數化查詢。

eg:

static void Main(string[] args)
{
    Console.WriteLine("請輸入使用者名稱");
    string username = Console.ReadLine();
    Console.WriteLine("請輸入密碼");
    string password = Console.ReadLine();
    //資料庫連接字串
    string connString = "Data Source=zhanghui; Initial Catalog=Ahui; User ID=sa; Pwd=111";
    //建立資料庫連接
    SqlConnection conn=new SqlConnection(connString);
    //開啟資料庫
    conn.Open();
    using (SqlCommand  ka=conn.CreateCommand())
    {
        ka.CommandText = "select count(*) from login where [email protected] and  [email protected]";
        //上面的可以先看成預留位置,通過下面的語句在給其賦值,。

        ka.Parameters.Add(new SqlParameter("UserName",username));

       //Parameters是其ka的一個屬性,是一個集合,通過調用Add來為其上面的預留位置來賦值。
        ka.Parameters.Add(new SqlParameter("Password",password));
        int i = Convert.ToInt32(ka.ExecuteScalar());
        if (i>0)
        {
            Console.WriteLine("登入成功");   
        }
        else
        {
            Console.WriteLine("使用者名稱或密碼錯誤?");
        }

    }
    Console.WriteLine("OK");
    Console.ReadKey();

上面的修改,是用了其試預留位置的欄位,來賦值,不是用參數的形式來設值,這樣子就堵注了SQL漏洞攻擊;

在其預留位置下面在為其預留位置賦值,是將拿輸入的東西當成字串的值,在資料庫中進行比較,如果有則登陸成功,否則登入失敗。

***在同一個串連中如果sqlDataReader沒有關閉,那麼是不能執行update之類的語句;

下面是一個登入的執行個體,但是出現不了自己想要的結果,總是說出錯,有誰做過可以幫我看看,謝謝。

代碼:

/*將第二個要用的資料庫連接必須重新寫在一個類中,進行調用,如果在一個資料庫連接字串中
        同時進行兩個sql語句的操作就會出現錯誤。
        這樣就相當於將其封裝起來,如果後面要用到,直接調用就行。
        */
       private void hui()
       {
           string connSting = "Data Source=zhanghui; Initial Catalog=Ahui; User ID=sa; Pwd=111;";
           SqlConnection conn = new SqlConnection(connSting);
           conn.Open();
           using (SqlCommand updata = conn.CreateCommand())
           {
               updata.CommandText = "update login Set errorTimes=errorTimes+1 where [email protected] ";
               updata.Parameters.Add(new SqlParameter("UserName", txtUserName.Text));
               updata.ExecuteNonQuery();
           }
       }

       private void btnLand_Click(object sender, EventArgs e)
       {
           string connString = "Data Source=zhanghui; Initial Catalog=Ahui; User ID=sa; Pwd=111;";
           SqlConnection conn=new SqlConnection(connString);
           conn.Open();
           using (SqlCommand lg=conn.CreateCommand())
           {
               lg.CommandText = "select * from login where [email protected]";
               lg.Parameters.Add(new SqlParameter("UserName",txtUserName.Text));
               using (SqlDataReader reader=lg.ExecuteReader())
               {
                   if (reader.Read())
                   {
                       int errorTime = reader.GetInt32(reader.GetOrdinal("errorTimes"));
                       if (errorTime > 3)
                       {
                           MessageBox.Show("登陸次數過多,禁止登入!");
                           return;
                       }
                       string AhuiPassword = reader.GetString(reader.GetOrdinal("Password"));
                       if (AhuiPassword==txtPassword.Text)
                       {
                           MessageBox.Show("登陸成功");
                       }
                       else
                       {
                           hui();  //調用了本類中上面的一個類。
                           MessageBox.Show("登入失敗");
                       }
                   }
                   else
                   {
                       MessageBox.Show("使用者名稱不存在");
                   }
                  
               }
           
           }

}

下面為資料庫和登入視窗

運行結果如下,剛開始還可以運行3次,說是登入失敗,現在只要是輸入就說登入此數過多,求大神支招

這個問題我自己一直解決不了,困擾我了很久,希望遇到大神,幫幫我。謝了。

【筆記】ADO.NET學習

聯繫我們

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