国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計(jì) > 正文

在asp.net中操作sql server數(shù)據(jù)庫的一些小技巧

2019-11-18 19:21:29
字體:
供稿:網(wǎng)友

1.給數(shù)據(jù)庫語句參數(shù)傳遞

向數(shù)據(jù)庫操作語句傳遞參數(shù)可以通過存儲(chǔ)過程實(shí)現(xiàn),這里給出另外兩種簡(jiǎ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.RegisterStartupScrjavascript>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ù)器,真一大遺憾。還有不知道編寫代碼的樣式和格式,使得給出的代碼顯得很零亂。


發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 荣昌县| 石楼县| 河西区| 方山县| 双峰县| 新兴县| 临汾市| 东源县| 仲巴县| 五原县| 永城市| 滦平县| 台安县| 岐山县| 报价| 游戏| 噶尔县| 依兰县| 昂仁县| 怀仁县| 台东县| 海南省| 达尔| 黄大仙区| 东山县| 融水| 新巴尔虎左旗| 台州市| 涡阳县| 隆回县| 田东县| 措美县| 罗平县| 闻喜县| 大邑县| 阳山县| 湄潭县| 手游| 农安县| 漯河市| 文昌市|