web.config 文件
<!--配置文件的字符串连接-->
<connectionStrings>
<add name="connStr" connectionString="Data Source=L;Initial Catalog=database;User ID=sa" providerName="System.Data.SqlClient" />
</connectionStrings>
default.aspx.cs 文件
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;//SQL数据库的必须类库
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//**************
//直接连接数据库
//string connStr="user id=sa;password=;initial catalog=database;data source=localhost";
//SqlConnection MyConn = new SqlConnection(connStr);
//********************
//通过配置文件的连接字符串来连接
SqlConnection conn=new SqlConnection(ConfigurationManager.ConnectionStrings["connStr"].ConnectionString);
string sql = "select top 20 * from tabale";
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "adinfos");
this.ad1.DataSource = ds.Tables["adinfos"];
this.ad1.DataBind();
conn.Close();
}
}
default.aspx 文件
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>无标题页</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DataList ID="ad1" runat=server>
<ItemTemplate><!--队列模板-->
<%#DataBinder.Eval(Container.DataItem,"ADInfoID").ToString()%>
</ItemTemplate>
</asp:DataList>
</div>
</form>
</body>
</html>