在ASP.NET中连接SQL Server的简单方法

编程学习 2021-07-04 22:40www.dzhlxh.cn编程入门
在ASP.NET中访问SQL Server数据库有两种方法,它们是System.Data.OleDb和System.Data.SqlClient.狼蚁网站SEO优化这段程序以System.Data.SqlClient为例访问本地数据库服务器.
首先导入名字空间:System.Data和System.Data.SqlClient.详细代码看源程序.
代码如下:

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<html>
<script language="C#" runat="server">
protected void Page_Load(Object Src, EventArgs E )
{
SqlConnection myConn = new SqlConnection("server=localhost;uid=sa;pwd=;database=pubs");
//创建对象SqlConnection
string strSQL="SELECT au_id,au_lname,au_fname,phone,address,city,zip FROM authors";
SqlDataAdapter myCmd = new SqlDataAdapter(strSQL, myConn);
//创建对象SqlDataAdapter
DataSet ds = new DataSet();
//创建对象DataSet
myCmd.Fill(ds);
//填充数据到Dataset
DataView source = new DataView(ds.Tables[0]);
MyDataGrid.DataSource = source ;
MyDataGrid.DataBind();
//将数据绑定到DataGrid
}
</script>
<body>
<h3><font face="Verdana">Simple SELECT to a DataGrid Control
</font></h3>
<ASP:DataGrid id="MyDataGrid" runat="server"
Width="600"
BackColor="#ccccff"
BorderColor="black"
ShowFooter="false"
CellPadding=3
CellSpacing="0"
Font-Name="Verdana"
Font-Size="8pt"
HeaderStyle-BackColor="#aaaadd"
MaintainState="false"
/>
</body>
</html>

Copyright © 2016-2025 www.dzhlxh.cn 金源码 版权所有 Power by

网站模板下载|网络推广|微博营销|seo优化|视频营销|网络营销|微信营销|网站建设|织梦模板|小程序模板