【IT168 技术文档】ASP.NET数据库在使用中有很多的优势,这些已经赢得了程序员们广泛的青睐。现在,我们就具体来看看ASP.NET数据库的应用。
对于一个熟练的ASP开发者来说,ASP.NET数据库的应用不但简单,而且功能还很强大。很多Web开发者就是因为这一点而选择ASP的,至今为止,他们一直认为ASP.NET数据库功能还不错,完全可以满足开发要求。
1.名字空间NameSpace
要使用ASP.NET数据库的功能,不可能离开名字空间NameSpace的使用。什么是名字空间,简单一点,名字空间就像Delphi中的控件,你必须将它们放入你的Form才能使用它们,同样,如果你要使用ASP.NET数据库的功能,你就必须先引用相应的名字空间。ASP.NET数据库的名字空间有这些:
<%@ Import NameSpace="System.Data.SQL"%>
<Script Language="VB" RunAt="Server">
Function createdatasource()
Dim conn AS SQLConnection
Dim connstr As String
Dim strsql AS String
Dim sqlCmd AS SQLDataSetCommand
Dim ds AS New DataSet
'连接数据库
connstr=
"Server=NHGA-D36KQ26TWB;DataBase=NorthWind; Pwd=;Uid=sa"
conn= New SQLConnection(connstr)
'SQL语句
strsql="Select * from Products "
'建立DataSet
sqlCmd=New SQLDataSetCommand(strsql,conn)
'将表Products加入DataSet
sqlCmd.FillDataset(ds,"Products")
return ds.Tables("Products").DefaultView
end Function
'绑定数据函数
sub BindGrid()
DataGrid1.DataSource=CreateDataSource()
DataGrid1.DataBind()
End Sub
'页面登录
Sub Page_Load(Source AS Object,E AS EventArgs)
CreatedataSource()
BindGrid()
End Sub
</Script>
<html>
<head>
<meta http-equiv="Content-Language" content="zh-cn">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<meta name="GENERATOR" content="Microsoft FrontPage 4.0">
<meta name="ProgId" content="FrontPage.Editor.Document">
<title>ASP.NET数据库使用</title>
</head>
<body>
<Form RunAt="Server">
<ASP:DataGrid id="DataGrid1" RunAt="Server" />
</Form>
</body>
</html>
<Script Language="VB" RunAt="Server">
Function createdatasource()
Dim conn AS SQLConnection
Dim connstr As String
Dim strsql AS String
Dim sqlCmd AS SQLDataSetCommand
Dim ds AS New DataSet
'连接数据库
connstr=
"Server=NHGA-D36KQ26TWB;DataBase=NorthWind; Pwd=;Uid=sa"
conn= New SQLConnection(connstr)
'SQL语句
strsql="Select * from Products "
'建立DataSet
sqlCmd=New SQLDataSetCommand(strsql,conn)
'将表Products加入DataSet
sqlCmd.FillDataset(ds,"Products")
return ds.Tables("Products").DefaultView
end Function
'绑定数据函数
sub BindGrid()
DataGrid1.DataSource=CreateDataSource()
DataGrid1.DataBind()
End Sub
'页面登录
Sub Page_Load(Source AS Object,E AS EventArgs)
CreatedataSource()
BindGrid()
End Sub
</Script>
<html>
<head>
<meta http-equiv="Content-Language" content="zh-cn">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<meta name="GENERATOR" content="Microsoft FrontPage 4.0">
<meta name="ProgId" content="FrontPage.Editor.Document">
<title>ASP.NET数据库使用</title>
</head>
<body>
<Form RunAt="Server">
<ASP:DataGrid id="DataGrid1" RunAt="Server" />
</Form>
</body>
</html>
以上是一个最简单的ASP.NET数据库应用,唯一功能就是列出NorthWind数据库Products表的所有记录。可以和ASP比较一下,发现这个程序是如此的简单。为了更好的了解数据库应用的基本框架,我们来看看这个数据库应用具体是怎样实现的。
页面登录时,调用CreateDataSource和BindGrid函数,CreateDataSource函数连接数据库并且建立DataView,BindGrid函数将数据绑定到DataGrid。有关这两个函数的具体语句,代码中均有说明。