1. 程式人生 > >ASP.NET連線SQL資料庫

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"%>