在ASP.NET中操作SQL Server的小技巧
2024-07-10 13:11:15
供稿:網友
國內最大的酷站演示中心!
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 [email protected]";
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:由于網絡速度太慢,不能將相關的顯示圖表傳到服務器,真一大遺憾。還有不知道編寫代碼的樣式和格式,使得給出的代碼顯得很零亂。