在asp.net中操作SqlServer数据库的一些小技巧

2007-9-12

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 LastName=@charname";

 

thisCommand.Parameters.Add("@charname",s);

 

 

 

可以看到,字符串s将参数“Ddbolio”传递给数据库操作语句中的参数charname

 

2.将数据库中不同表内的数据读入到数据集DataSet

 

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

 

 

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","");

 

 

可以看到,在数据集ds中新生成了两个临时表“myemployees”和“myCustomers”。为验证这两个表中数据确实已读入数据集ds中,通过数据读取操作将表“myemployees”中对应于属性“Hiredate”的第一行赋值给字符型变量t1,将表“myCustomers”中对应于属性“ContactTitle”的第一行赋值给字符型变量t2,并通过JavaStript函数“alert()”将这些变量显示到弹出窗口中。Page.RegisterStartupScript方法用于发出客户端脚本块,其第一个参数为标志位,用户可以任意选取,第二个参数为JavaScript脚本,这里alert函数用来弹出MessageBox对话框,我们将参数t1t2传入该脚本中,使其在MessageBox中显示出来。

技术支持



服务在线

市场部:

Contact Us.
联系我们!

客服: 1131099230
销售部:

Contact Us.
联系我们!

客服: 1151480445
企划部: Contact Us.
联系我们! 客服: 1134615268
技术部: Contact Us.
联系我们! 客服: 1131412366

热线电话:

0516-83712388  82861699
客户留言

查看留言



友情链接: 都市信息报 今日徐州 徐州人防(民防)网 中国淮海网 徐州古彭地下商场

Copyright©2006-2010 徐州华旗投资管理有限公司 All Rights Reserved.
公司地址:江苏省徐州市解放北路2号汇源置地广场1510室
电话:0516-8371 2388 邮箱:Support@hq010.net
苏ICP备09084468号