|
1.給數(shù)據(jù)庫語句參數(shù)傳遞
向數(shù)據(jù)庫操作語句傳遞參數(shù)可以通過存儲(chǔ)過程實(shí)現(xiàn),這里給出另外兩種簡便易捷的方法:
可以在C#中通過字符串操作將參數(shù)直接傳入SQL語句變量中,例如:
string s="Davolio";
string sql= "select * from employees where LastName="+"'"+s+"'"
相當(dāng)于寫入SQL語句:
select * from employees where LastName='Davolio'
也可以通過thisCommand.Parameters.Add()方法實(shí)現(xiàn),如下所示:
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將參數(shù)“Ddbolio”傳遞給數(shù)據(jù)庫操作語句中的參數(shù)charname。
2.將數(shù)據(jù)庫中不同表內(nèi)的數(shù)據(jù)讀入到數(shù)據(jù)集DataSet中
SqlDataAdapter的Fill方法可以填充已知數(shù)據(jù)集,并且為每個(gè)填充項(xiàng)創(chuàng)建一個(gè)臨時(shí)表,可以通過對(duì)該表的訪問來讀取數(shù)據(jù)集中的相關(guān)數(shù)據(jù)。其相關(guān)操作如下所示:
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>");
可以看到,在數(shù)據(jù)集ds中新生成了兩個(gè)臨時(shí)表“myemployees”和“myCustomers”。為驗(yàn)證這兩個(gè)表中數(shù)據(jù)確實(shí)已讀入數(shù)據(jù)集ds中,通過數(shù)據(jù)讀取操作將表“myemployees”中對(duì)應(yīng)于屬性“Hiredate”的第一行賦值給字符型變量t1,將表“myCustomers”中對(duì)應(yīng)于屬性“ContactTitle”的第一行賦值給字符型變量t2,并通過JavaStript函數(shù)“alert()”將這些變量顯示到彈出窗口中。Page.RegisterStartupScript方法用于發(fā)出客戶端腳本塊,其第一個(gè)參數(shù)為標(biāo)志位,用戶可以任意選取,第二個(gè)參數(shù)為JavaScript腳本,這里alert函數(shù)用來彈出MessageBox對(duì)話框,我們將參數(shù)t1和t2傳入該腳本中,使其在MessageBox中顯示出來。
ps:由于網(wǎng)絡(luò)速度太慢,不能將相關(guān)的顯示圖表傳到服務(wù)器,真一大遺憾。還有不知道編寫代碼的樣式和格式,使得給出的代碼顯得很零亂。
AspNet技術(shù):在asp.net中操作sql server數(shù)據(jù)庫的一些小技巧,轉(zhuǎn)載需保留來源!
鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標(biāo)記有誤,請(qǐng)第一時(shí)間聯(lián)系我們修改或刪除,多謝。