天天看點

在asp.net中操作sql server資料庫的一些小技巧

1.給資料庫語句參數傳遞

向資料庫操作語句傳遞參數可以通過存儲過程實作,這裡給出另外兩種簡便易捷的方法:

可以在c#中通過字元串操作将參數直接傳入sql語句變量中,例如:

strings="davolio";

stringsql="select*fromemployeeswherelastname="+"'"+s+"'"

相當于寫入sql語句:

select*fromemployeeswherelastname='davolio'

也可以通過thiscommand.parameters.add()方法實作,如下所示:

sqlconnectionthisconnection=newsqlconnection

("datasource=(local);initialcatalog=northwind;uid=sa;pwd=");

thisconnection.open();

sqlcommandthiscommand=thisconnection.createcommand();

thiscommand.commandtext=

"select*fromemployeeswhere

thiscommand.parameters.add("@charname",s);

可以看到,字元串s将參數“ddbolio”傳遞給資料庫操作語句中的參數charname。

2.将資料庫中不同表内的資料讀入到資料集dataset中

sqldataadapter的fill方法可以填充已知資料集,并且為每個填充項建立一個臨時表,可以通過對該表的通路來讀取資料集中的相關資料。其相關操作如下所示:

try

{

}

catch(exceptionex)

thisconnection.close();

stringsql1="select*fromemployees";

stringsql2="select*fromcustomers";

sqldataadaptersda=newsqldataadapter(sql1,thisconnection);

datasetds=newdataset();

sda.fill(ds,"myemployees");

sda.dispose();

sqldataadaptersda1=newsqldataadapter(sql2,thisconnection);

sda1.fill(ds,"mycustomers");

sda1.dispose();

stringt1=ds.tables["myemployees"].rows[0]["hiredate"].tostring();

stringt2=ds.tables["mycustomers"].rows[0]["contacttitle"].tostring();

page.registerstartupscript("aa","<scriptlanguage=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:由于網絡速度太慢,不能将相關的顯示圖表傳到伺服器,真一大遺憾。還有不知道編寫代碼的樣式和格式,使得給出的代碼顯得很零亂。