当前位置: 首页 > 图文教程 > 网络编程 > ASP.NET > 在asp.net中操作sql server数据库的一些小技巧

ASP.NET
FreeTextBox(版本3.1.6)在ASP.Net 2.0中使用方法
.NET 常用功能和代码小结
在 .NET Framework 2.0 中未处理的异常导致基于 ASP.NET 的应用程序意外退出
asp.net IList查询数据后格式化数据再绑定控件
asp.net sql存储过程
asp.net 简单实现禁用或启用页面中的某一类型的控件
asp.net(c#)获取内容第一张图片地址的函数
The remote procedure call failed and did not execute的解决办法
ASP.NET 在线文件管理
asp.net 读取并修改config文件实现代码
ASP.NET Cookie 操作实现
asp.net Silverlight中的模式窗体
Silverlight中动态获取Web Service地址
asp.net Silverlight应用程序中获取载体aspx页面参数
asp.net 水晶报表隔行换色实现方法
asp.net 获取Gridview隐藏列的值
手动把asp.net的类生成dll文件的方法
asp.net 使用ObjectDataSource控件在ASP.NET中实现Ajax真分页
动态指定任意类型的ObjectDataSource对象的查询参数
asp.net Md5的用法小结

ASP.NET 中的 在asp.net中操作sql server数据库的一些小技巧


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-08-14   浏览: 75 ::
收藏到网摘: n/a

1.给数据库语句参数传递

向数据库操作语句传递参数可以通过存储过程实现,这里给出另外两种简便易捷的方法:

可以在C#中通过字符串操作将参数直接传入SQL语句变量中,例如:

strings="Davolio";

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

相当于写入SQL语句:

select*fromemployeeswhereLastName='Davolio'
也可以通过thisCommand.Parameters.Add()方法实现,如下所示:

strings="Davolio";


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方法可以填充已知数据集,并且为每个填充项创建一个临时表,可以通过对该表的访问来读取数据集中的相关数据。其相关操作如下所示:


SqlConnectionthisConnection=newSqlConnection

("DataSource=(local);InitialCatalog=Northwind;UID=sa;PWD=");

try

{

thisConnection.Open();

}

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:由于网络速度太慢,不能将相关的显示图表传到服务器,真一大遗憾。还有不知道编写代码的样式和格式,使得给出的代码显得很零乱。