1. 程式人生 > >asp.net實驗二:連線sql server 2008資料庫

asp.net實驗二:連線sql server 2008資料庫

   要求,通過ASP.NET 與sql server 2008進行連線,並測試資料。

   任意在asp.net應用程式中新增一個web窗體,如test.aspx

   在tesst.aspx.cs中新增程式碼進行測試:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;     //注意需要新增此句

namespace aspnet3
{
    public partial class datatest : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string strconn = "server=localhost;uid=sa;pwd=longlt;database=School"; 
            SqlConnection conn = new SqlConnection(strconn);   //建立連線 
            string sql = "select * from students"; 
            conn.Open(); 
            SqlCommand cmd = new SqlCommand(sql, conn);      //執行查詢
            Response.Write("連線成功");
            SqlDataReader dr = cmd.ExecuteReader();          //查詢結果
            if (dr.Read())
            {
                 //利用dr[索引]對資料庫表進行操作,dr[]返回object;
                    //可以用欄位做索引,也可用列號0,1..做索引
                Response.Write(dr[0].ToString() + "<br>");
            }

           // this.Lab.Text = "suc";
        }
    }
}