在ASP.NET中操作SQL Server的小技巧

1.給數據庫語句參數傳遞
  
  向數據庫操作語句傳遞參數可以通過存儲過程實現,這裏給出另外兩種簡便易捷的方法:
  
  可以在C#中通過字符串操作將參數直接傳入SQL語句變量中,例如:
  
  string s="Davolio";
  
  string sql= "select * from employees where LastName="+"'"+s+"'"
  
  相當於寫入SQL語句:
  
  select * from employees where LastName='Davolio'也可以通過thisCommand.Parameters.Add()方法實現,如下所示:
  
  string s="Davolio";
  
  SqlConnection thisConnection=new SqlConnection
  
  ("Data Source=(local);Initial Catalog=Northwind;UID=sa;PWD=");
  
  thisConnection.Open ();
  
  SqlCommand thisCommand=thisConnection.CreateCommand ();
  
  thisCommand.CommandText =
  
  " select * from employees where LastName=@charname";
  
  thisCommand.Parameters.Add("@charname",s);
  
  可以看到,字符串s將參數“Ddbolio”傳遞給數據庫操作語句中的參數charname.
  
  2.將數據庫中不同表內的數據讀入到數據集DataSet中
  
  SqlDataAdapter的Fill方法可以填充已知數據集,並且爲每個填充項創建一個臨時表,可以通過對該表的訪問來讀取數據集中的相關數據。其相關操作如下所示:
  
  SqlConnection thisConnection=new SqlConnection
  
  ("Data Source=(local);Initial Catalog=Northwind;UID=sa;PWD=");
  
  try
  
  {
  
  thisConnection.Open ();
  
  }
  
  catch(Exception ex)
  
  {
  
  thisConnection.Close ();
  
  }
  
  string sql1="select * from employees";
  
  string sql2="select * from Customers";
  
  SqlDataAdapter sda=new SqlDataAdapter(sql1,thisConnection);
  
  DataSet ds= new DataSet();
  
  sda.Fill(ds,"myemployees");
  
  sda.Dispose();
  
  SqlDataAdapter sda1=new SqlDataAdapter(sql2,thisConnection);
  
  sda1.Fill(ds,"myCustomers");
  
  sda1.Dispose();
  
  string t1=ds.Tables["myemployees"].Rows[0]["Hiredate"].ToString();
  
  string t2=ds.Tables["myCustomers"].Rows[0]["ContactTitle"].ToString();
  
  Page.RegisterStartupScript("aa","<;script language=javascript>alert('t1="+t1+",t2="+t2+"');<;/script>");
  
  可以看到,在數據集ds中新生成了兩個臨時表“myemployees”和“myCustomers”。爲驗證這兩個表中數據確實已讀入數據集ds中,通過數據讀取操作將表“myemployees”中對應於屬性“Hiredate”的第一行賦值給字符型變量t1,將表“myCustomers”中對應於屬性“ContactTitle”的第一行賦值給字符型變量t2,並通過JavaStript函數“alert()”將這些變量顯示到彈出窗口中。Page.RegisterStartupScript方法用於發出客戶端腳本塊,其第一個參數爲標誌位,用戶可以任意選取,第二個參數爲JavaScript腳本,這裏alert函數用來彈出MessageBox對話框,我們將參數t1和t2傳入該腳本中,使其在MessageBox中顯示出來。
  
  ps:由於網絡速度太慢,不能將相關的顯示圖表傳到服務器,真一大遺憾。還有不知道編寫代碼的樣式和格式,使得給出的代碼顯得很零亂。

發佈了54 篇原創文章 · 獲贊 3 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章