ASP.NET连接SQL数据库

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;
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string connStr = "server=localhost;database=pubs;uid=sa;pwd=123456";
        //string str = System.Configuration.ConfigurationManager.ConnectionStrings[connStr].ToString();
        SqlConnection conn = new SqlConnection(connStr);
        conn.Open();
        SqlDataAdapter sda = new SqlDataAdapter("select * from authors", conn);//sqlDataAdapter是连接数据库和数据集之间的桥梁
        DataSet ds = new DataSet();
        sda.Fill(ds, "authors");   //填充数据集
        if (ds.Tables[0].Rows.Count == 0)
        {
            Response.Write("数据库中无数据");

        }
        else
        {
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                Response.Write(ds.Tables["authors"].Rows[i][1]);
                Response.Write("________");
                Response.Write(ds.Tables["authors"].Rows[i]["au_fname"]);
                Response.Write("<br>");
            }
        }
        conn.Close();

    }
}
注意:一定要把下面这句Debug="true"写上

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default"  Debug="true"%> 

你可能感兴趣的:(ASP.NET连接SQL数据库)